2016-07-11 12 views
-1

私はCでpthreadを探しています。だから私は新しいです。私はpthreadコードの中でポインタの構文と役割を学びたいと思っています。コードによると私の過ちは何ですか?私は何をしたのかわかりません。pthreadライブラリの基本的な例が正しく動作しません

戻り値を確認しようとしているときpthread_create()私は間違った/ランダムな値を取得しています。

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

int *f_1,*f_2,*f_3,*f_4; 

void p1(void *a); 
void p2(void *a); 
void p3(void *a); 
void p4(void *a); 

int main(void){ 
pthread_t thread_1, thread_2, thread_3, thread_4; 
int *x=1,*y=2,*z=3,*w=4; 

f_1=pthread_create(&thread_1, NULL, p1,(void *)x); 
f_2=pthread_create(&thread_2, NULL, p2,(void *) y); 
f_3=pthread_create(&thread_3, NULL, p1,(void *) z); 
f_4=pthread_create(&thread_4, NULL, p1,(void *) w); 

pthread_join(thread_1,NULL); 
pthread_join(thread_2,NULL); 
pthread_join(thread_3,NULL); 
pthread_join(thread_4,NULL); 


printf("Hi! From %d. thread!",f_1); 
printf("Hi! From %d. thread!",f_2); 
printf("Hi! From %d. thread!",f_3); 
printf("Hi! From %d. thread!",f_4); 

return 0; 
} 
void p1(void *a){ 
f_1=(int *)a; 
} 

void p2(void *a){ 
f_2=(int *)a; 
} 

void p3(void *a){ 
f_3=(int *)a; 
} 

void p4(void *a){ 
f_4=(int *)a; 
} 
+0

'明らかに、私がしたこと。 "...質問:あなたはどうしたのですか? –

+0

少なくとも、あなたがしようとしていたことや、このコードで何が問題になっているのか説明できますか? –

+0

いくつかのウェブサイトからはコンパイルされていませんでした。 – QatarNotAlone

答えて

0

pthread_create()あなたはint *(ポインタ)でそれを保存しようとしている、intを返します。これは実装定義の動作です。

f_1=pthread_create(&thread_1, NULL, p1,(void *)x); 
f_2=pthread_create(&thread_2, NULL, p2,(void *) y); 
f_3=pthread_create(&thread_3, NULL, p1,(void *) z); 
f_4=pthread_create(&thread_4, NULL, p1,(void *) w); 

次は、印刷のポインタ、undefined behaviorを呼び出し

printf("Hi! From %d. thread!",f_1); 
printf("Hi! From %d. thread!",f_2); 
printf("Hi! From %d. thread!",f_3); 
printf("Hi! From %d. thread!",f_4); 

から%dを使用しています。

上記の両方の問題を解決するには、f_nの変数はすべて、int *ではなくintタイプである必要があります。

スレッド関数の関数プロトタイプは、関数void *を返すとvoid *を受け付けて

void *(*start_routine) (void *) 

である、と述べました。関数のシグネチャとスレッド関数の定義をそれに従って変更することができます。

+0

あなたは、pthread_create()を使用して、サブfuctionsからの戻り値が得られないと言っていますか? – QatarNotAlone

+0

@outSider 'pthread_create()'関数呼び出し自体の戻り値については、リンクされたマニュアルページを参照してください。 –

+0

よろしくお願いします。 – QatarNotAlone

関連する問題