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



我正试图通过从数组中下一个项的内存地址访问它,用函数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 %dn", 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;
}

最新更新