2017-02-26 61 views
1

這是我的代碼的縮寫版本。我應該澄清,「initializeGrid()」的行爲是正確的,所以爲了簡潔起見,我沒有包括它。我試圖讓「threadFunction()」在args中打印值,但它不起作用。請幫忙!爲什麼我的線程不能正常產卵? C

#include <pthread.h> 
#include <math.h> 
#include <stdio.h> 
#include <stdlib.h> 
#include <memory.h> 

int gridSize = 12; 

typedef struct threadParameter { 
    float * grid; 
    int top; 
    int bot; 
}threadParameter; 

void* threadFunction(void* args) { 

    threadParameter *param = (threadParameter*) args; 
    printf("%d, %d", param->bot, param->top); 
    return 0; 

} 

int main(int argc, char *argv[]) { 

    int numProcs = 4; 

    pthread_t * threadsArr = malloc(numProcs * sizeof(pthread_t)); 

    float mainGrid[gridSize][gridSize]; 
    memset(mainGrid, 0, gridSize*gridSize * sizeof(float)); 
    initializeGrid(1.0, 2.0, 3.0, 4.0, mainGrid); 

    threadParameter t = {&mainGrid[0][0], 0, gridSize}; 
    int ret = pthread_create(&threadsArr[0], 0, threadFunction, (void*)&t); 

} 

回答

2

您的main()函數在調用pthread_create()後立即返回。

main()返回時,進程退出並終止,同時生成每個線程。

您需要添加pthread_join()調用以等待線程終止。每pthread_join() POSIX standard

pthread_join()功能應暫停調用 線程的執行,直到目標thread終止

像這樣:

int main(int argc, char *argv[]) { 

    int numProcs = 4; 

    pthread_t * threadsArr = malloc(numProcs * sizeof(pthread_t)); 

    float mainGrid[gridSize][gridSize]; 
    memset(mainGrid, 0, gridSize*gridSize * sizeof(float)); 
    initializeGrid(1.0, 2.0, 3.0, 4.0, mainGrid); 

    threadParameter t = {&mainGrid[0][0], 0, gridSize}; 
    int ret = pthread_create(&threadsArr[0], 0, threadFunction, (void*)&t); 

    pthread_join(threadsArr[0], NULL); 
} 
+0

非常感謝你,@Andrew漢勒!這正是問題所在。感謝您的快速和詳細的回覆! – SupposedlySleeping

+1

解決該問題的另一種方法是執行'pthread_exit'而不是'main'的隱式返回。這使進程保持活動狀態,並讓所有其他線程按其選擇的方式終止。 –