2011-07-11 50 views
1

我正在用線程逼近C編程,我無法使該程序正常工作。基本上有一個向量包含k個元素,n個線程,每個線程必須計算其k/n個元素的最大值。線程執行問題

我的代碼是(請注意這不是整個代碼):

// Struct code used later 
struct maxStruct 
{ 
    double *vettore; 
    int dimensione; 
}; 

// Gathering data input from user 

[ . . . ] 
vector = (double *) malloc (dimensione * sizeof(double)); 
pid_thread = (int *) malloc (numero_thread * sizeof(int)); 
thread = (pthread_t *) malloc (numero_thread * sizeof(pthread_t)); 

// Generating the vector 

[ . . . ] 
for (i = 0; i < numero_thread; i++) 
    { 
     e = generaStruct(i, vettore, dimensione, numero_thread); 
     if (status = pthread_create(&thread[i], NULL, calcolaMassimo, (void *) e)) 
       { 
        pthread_perror("pthread_join", status); 
        exit(1); 
       } 
    } 

//Note that the function doesn't calculate the max, I've coded it in this way 
//in order to see whether it was being called by each thread and apparently it is not. 
void *calcolaMassimo(void * e) 
{ 
    printf("Sono chiamata!!\n"); 
    struct maxStruct *sottoVettore = e; 

    printf("Dimensione: %d\n", ((*sottoVettore).dimensione)); 

} 

顯然,這個功能沒有被每一個線程調用,我想不通爲什麼。你能幫我解決這個問題嗎?

+0

你怎麼知道函數沒有被每個線程調用? Printf不是線程安全的;除非你同步訪問它,否則你不會得到你期望的結果。 – antlersoft

+0

@antlersoft:在Linux的libc中,printf'實際上是線程安全的。 – 2011-07-11 18:02:49

+0

創建線程後你在做什麼? –

回答

2

首先,小挑剔,寫作(*sottoVettore).dimensione)的地道方式是sottoVettore->dimensione

退出main()時,包含所有線程的進程將退出。我知道你說你加入了你的實際代碼,所以這不應該是一個問題,但如果你沒有加入測試代碼,那麼這可能是一個問題。

也可能問題不在於每個線程中的代碼沒有執行,而是這些語句實際上沒有達到stdout。您可能想在calcolaMassimo的末尾嘗試fflush(stdout),看看是否會改變這些事情。