1.
read_thread从终端输入一个个的字符,当遇到q字符时,发送cond_signal
write_thread一直在等侍signal,当收到read_thread发来的signal之后打印退出
2. 源码
-
cong@msi:/work/test/thread/4cond$ cat cond.c
-
#include "utils.h"
-
pthread_mutex_t thread_mutex = PTHREAD_MUTEX_INITIALIZER;
-
pthread_cond_t thread_cond = PTHREAD_COND_INITIALIZER;
-
int c;
-
void* read_thread(void* arg)
-
{
-
while((c=getchar()) != 'q');
-
printf("read=%c\n", c);
-
printf("send signal\n");
-
pthread_cond_signal(&thread_cond);
-
return NULL;
-
}
-
-
void* write_thread(void* arg)
-
{
-
pthread_mutex_lock(&thread_mutex);
-
printf("wait cond\n");
-
pthread_cond_wait(&thread_cond, &thread_mutex);
-
printf("write=%c\n", c);
-
pthread_mutex_unlock(&thread_mutex);
-
}
-
-
int main ( int argc, char *argv[] )
-
{
-
pthread_t thread_id1;
-
pthread_t thread_id2;
-
void* thread_result;
-
int status;
-
-
status = pthread_create(&thread_id1, NULL, read_thread, NULL);
-
status = pthread_create(&thread_id2, NULL, write_thread, NULL);
-
-
status = pthread_join(thread_id1, &thread_result);
-
status = pthread_join(thread_id2, &thread_result);
-
-
return EXIT_SUCCESS;
-
}
运行结果
-
cong@msi:/work/test/thread/4cond$ ./cond
-
wait cond
-
a
-
b
-
c
-
d
-
e
-
f
-
q
-
read=q
-
send signal
-
write=q
4cond.rar (下载后改名为4cond.tar.gz)
阅读(1173) | 评论(0) | 转发(0) |