スレッドを使用した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));
}
どうやらこの機能は、各スレッドによって呼び出されていないと私は理由を理解することはできません。あなたは私がこの問題を解決するのを助けてくれますか?
関数が各スレッドによって呼び出されていないことをどのように知っていますか? Printfはスレッドセーフではありません。アクセスを同期させない限り、期待した結果が得られません。 – antlersoft
@antlersoft:Linuxのlibcで 'printf'は実際にはスレッドセーフです。 –
スレッドを作成した後は何をしていますか? –