我正在尝试创建一个必须创建一系列 pthread 的函数。我试图通过为每个线程分配一个唯一的 int t 来跟踪它。然而,当我尝试创建多个线程时,每当我在主函数中增加 t 的值时,它的值就会发生变化。它应该按值传递,那么为什么要改变呢?
// Struct //
typedef struct threadArg {
int verbose;
int listSize;
int thread;
int (*list)[];
} threadArg;
// In main //
for(t=0; t < numThreads; t++){
printf("Creating thread %ld...\n", t);
struct threadArg arg = {
.verbose = verbose,
.list = &arr,
.listSize = size,
.thread = t
};
printf("t: %d\n", (arg.thread));
status = pthread_create(&threadID[t], NULL, threadSort, (void*)&arg);
if (status){
printf("ERROR: failed to create thread", t);
exit(-1);
}
}
// Thread Sort function //
void *threadSort(void* arguments) {
// *** Bubble Sort ***
threadArg* arg = (threadArg*) arguments;
int verbose = arg->verbose;
int size = arg->listSize;
int (*arr)[size] = arg->list;
int t = arg->thread;
if (verbose & INIT) { printf("Thread %d initalized!\n", t); }
}
感谢您的帮助, 沃利
最佳答案
It should be pass by value
不,这一行“通过引用”传递它,即传递 arg
的地址:
status = pthread_create(&threadID[t], NULL, threadSort, (void*)&arg)
代码中的 arg
实例会在循环的每次迭代中使用、销毁和重新创建。
要修复此修改,您可以编写如下代码:
void * threadSort(void * arguments);
[...]
struct threadArg arg = {
.verbose = verbose,
.list = &arr,
.listSize = size,
.thread = 0,
};
struct threadArg args[t] = {0};
for(t=0; t < numThreads; t++)
{
printf("Creating thread %ld...\n", t);
args[t] = arg;
args[t].thread = t;
printf("t: %d\n", arg.thread);
status = pthread_create(threadID + t, NULL, threadSort, args + t);
[...]
这引入了一个struct arg
数组,其中每个独立线程都有一个元素,由threadArg
的值初始化,该数组不在其他地方使用,但有一个共同的线程wag 的初始化被传递给线程函数。
关于c - 传递给 pthread 后结构发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22489359/