如何通过访问其内存地址将局部变量从一个线程传递到另一个线程?

how can I pass an local variable from a thread to another thread by accessing its memory address?

我试图通过从其内存地址访问数组中下一项的值,并将其作为函数 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);
    }

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

与其立即取消引用转换后的参数,不如直接将其作为 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;
}