-1
我試圖創建一個必須創建一系列pthread的函數。我試圖通過分配一個唯一的int t來跟蹤每個線程。但是,當我嘗試創建多個線程時,每當我在主函數中增加它時,t的值都會改變。它應該通過價值傳遞,爲什麼它會改變?傳遞給pthread後的結構更改
// 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); }
}
感謝你的幫助, 沃利
啊我明白了。我認爲在循環中創建結構會爲每個複製創建單獨的實體。我想我談到C時有點生疏。非常感謝! –