首页 > 解决方案 > 如何通过访问其内存地址将局部变量从一个线程传递到另一个线程?

问题描述

我试图通过从其内存地址访问它来用函数TaskCode中作为参数的值覆盖数组中下一项的值。我尝试了很多组合,但它并没有像我预期的那样工作。

    #include <pthread.h>
    #include <stdio.h>
    #include <stdlib.h>
    #include <assert.h>
    
    #define NUM_THREADS 5
    
    void* TaskCode(void* argument) {
        int tid = *((int*)argument); //set tid to value of thread
        tid++;  // go to next memory address of thread_args
        tid = *((int*)argument); // set that value to the value of argument
        printf("\nI have the value: \" %d \" and address: %p! \n", tid, &tid);
        return NULL;
    }
    
    int main(int argc, char* argv[]) 
    {
        pthread_t threads[NUM_THREADS]; // array of 5 threads
        int thread_args[NUM_THREADS +1 ];   // array of 6 integers
        int rc, i;
    
            for (i = 0; i < NUM_THREADS; ++i) {/* create all threads */
                thread_args[i] = i; // set the value thread_args[i] to 0,1...,4
                printf("In main: creating thread %d\n", i);
                rc = pthread_create(&threads[i], NULL, TaskCode,
                    (void*)&thread_args[i]);
                assert(0 == rc);
            }
        /* wait for all threads to complete */
        for (i = 0; i < NUM_THREADS; ++i) {
            rc = pthread_join(threads[i], NULL);
            assert(0 == rc);
        }
        exit(EXIT_SUCCESS);
    }

标签: cmultithreadingpthreads

解决方案


在您的线程函数中,tid是数组中特定成员的。对此变量的任何更改都不会反映在其他地方。thread_argsmain

与其立即取消引用转换后的参数,不如直接将其作为int *. 然后您可以对其进行指针运算并进一步取消引用它。

void* TaskCode(void* argument) {
    int *tid = argument;
    tid++;
    *tid = *((int*)argument);
    printf("\nI have the value: \" %d \" and address: %p! \n", *tid, (void *)tid);
    return NULL;
}

推荐阅读