- 论坛徽章:
- 0
|
本帖最后由 crazyhadoop 于 2012-12-21 09:12 编辑
求教的问题描述:
两个线程,
想实现的步骤如下,read_thread线程工作16次后send_thread线程才工作,
但是调试结果显示只能执行一次read_thread,打印一次read_thread running程序就停止了,
请教各位,程序是哪里问题?
【fix】 两个线程之间同步,一个信号量就可以了- #include <stdio.h>
- #include <stdlib.h>
- #include <string.h>
- #include <errno.h>
- #include <pthread.h>
- #include <semaphore.h>
- sem_t rd_sem,net_sem;
- int count=0;
-
- void* read_thread(void* arg)
- {
- int rd_ret=0;
- int i=0;
- while(1)
- {
-
- count+=1;
- printf("read_thead running!\n");
- if(count==16)
- {
- count=0;
- sem_post(&net_sem);
- }
-
- sleep(2);
- }
-
-
- }
-
- void* send_thread(void* arg)
- {
- while(1)
- {
- sem_wait(&net_sem);
- printf("Send dates to PC\n");
- }
- }
- int main()
- {
- int ret=0;
- pthread_t pid1,pid2;
- [u]ret=sem_init(&rd_sem,0,1);//保证先启动读线程
- [/u] ret=sem_init(&net_sem,0,0);
- if(ret!=0)
- {
- perror("sem_init");
- }
- ret = pthread_create(&pid1, NULL,read_thread, NULL);
- if(ret!=0)
- {
- perror("read_thread");
- }
- ret = pthread_create(&pid2, NULL,send_thread, NULL);
- if(ret!=0)
- {
- perror("send_thread");
- }
- pthread_join(pid2,NULL);
- return 0;
- }
复制代码 |
|