2011-07-11 9 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'は実際にはスレッドセーフです。 –

+0

スレッドを作成した後は何をしていますか? –

答えて

2

まず、マイナーニットピック、(*sottoVettore).dimensione)を書くための慣用方法はsottoVettore->dimensioneです。

main()が終了すると、すべてのスレッドを含むプロセスが終了します。私はあなたがあなたに参加しているということは実際のコードなので、問題ではないはずですが、あなたがテストコードに参加していない場合、それが問題になる可能性があることを知っています。

問題は、各スレッドのコードが実行されていないが、実際には文がstdoutに到達していないことではない可能性があります。 calcolaMassimoの末尾にあるfflush(stdout)を試して、変更があるかどうか確認してください。