2014-03-18 72 views
-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); } 
} 

感謝你的幫助, 沃利

回答

0

應該按值傳遞

沒有,這條線將其傳遞「通過引用」,也就是通過地址arg

status = pthread_create(&threadID[t], NULL, threadSort, (void*)&arg) 

的實例你的代碼中的被用於循環的每次迭代中並被重新創建。

爲了解決這個問題modfiy您的代碼等如下:

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的陣列爲每個sperate螺紋的元件中,通過的threadArg的值,這是不別處使用,但具有被nitialised whag的一個通用初始化被傳遞給線程函數。

+0

啊我明白了。我認爲在循環中創建結構會爲每個複製創建單獨的實體。我想我談到C時有點生疏。非常感謝! –