私もこの辺のAPIはあまり使ったことが無いので、
自信を持ってお勧めできるほどではありませんが、
pthread_cond
系のほうが素直にスレッド間通信ができるのではないかと思います。
細かい点は私は説明しきれないので、参考URLのような参考情報を読んでみてください。
※追記:書き忘れていましたが、pthreadを使用する場合は、コンパイル時に-pthread
オプションをつけましょう。
以下のサンプルプログラムは、スレッド#1は待機してスレッド#2からのシグナルで起こしてもらってprint
を実行してまた待機を繰り返す処理です。
※エラーハンドリングは省略しています。
lang
1#include <stdio.h>
2#include <unistd.h>
3#include <pthread.h>
4
5void *f_thread1(void *);
6void *f_thread2(void *);
7
8typedef struct {
9 pthread_mutex_t mutex;
10 pthread_cond_t cond;
11} pthread_conds;
12
13int main()
14{
15 pthread_t th1, th2;
16 pthread_conds conds;
17
18 pthread_mutex_init(&conds.mutex, NULL);
19 pthread_cond_init(&conds.cond, NULL);
20
21 pthread_create(&th1, NULL, f_thread1, (void *)&conds);
22 pthread_create(&th2, NULL, f_thread2, (void *)&conds.cond);
23
24 getchar();
25 pthread_cond_destroy(&conds.cond);
26
27 return 0;
28}
29
30void *f_thread1(void *arg)
31{
32 pthread_conds *condsp;
33
34 condsp = (pthread_conds *)arg;
35 while (1)
36 {
37 pthread_cond_wait(&condsp->cond, &condsp->mutex);
38 pthread_mutex_unlock(&condsp->mutex);
39 printf("f_thread1\n");
40 }
41}
42
43void *f_thread2(void *arg)
44{
45 pthread_cond_t *condp;
46
47 condp = (pthread_cond_t *)arg;
48 while (1)
49 {
50 pthread_cond_signal(condp);
51 sleep(2);
52 }
53}
参考URL:
Man page of PTHREAD_COND (JM Project)
一般的なスレッド: POSIX スレッドの説明: 第3回 (IBM developerWorks)
pthread のキャンセル (塩兄コラム)
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2014/11/03 09:58
2014/11/03 10:37
2014/11/03 11:23
2014/11/04 14:38
2014/11/05 00:44
2014/11/06 03:44