一个线程同步问题!

PonyCheng2019 2016-12-19 11:37:59
我想在主线程中读取标准输入,将读取的数据保存在buff中,读完一行再通知writer线程打印buff里的内容,但是
我发现writer似乎没有执行啊,代码如下,希望有高人解答一下!

#include <stdlib.h>
#include <string.h>
#include <pthread.h>
#include <unistd.h>

struct data
{
pthread_mutex_t lock;
pthread_cond_t cond;
char buff[BUFSIZ];
};

struct data shared_data;

void *writer(void *arg)
{
while (1)
{
pthread_mutex_lock(&shared_data.lock);
pthread_cond_wait(&shared_data.cond, &shared_data.lock);
printf("writer: %s\n", shared_data.buff);
pthread_mutex_unlock(&shared_data.lock);
}
return NULL;
}

int main(int argc, const char *argv[])
{
pthread_t writer_tid;
memset(shared_data.buff, 0, sizeof(shared_data.buff));
pthread_mutex_init(&shared_data.lock, NULL);
pthread_cond_init(&shared_data.cond, NULL);

pthread_create(&writer_tid, NULL, writer, NULL);

while (1)
{
pthread_mutex_lock(&shared_data.lock);
printf("reader: ");
if (fgets(shared_data.buff, BUFSIZ, stdin))
{
pthread_cond_signal(&shared_data.cond);
pthread_mutex_unlock(&shared_data.lock);
}
}
pthread_join(writer_tid, NULL);

return 0;
}
...全文
276 1 打赏 收藏 转发到动态 举报
AI 作业
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
ipqtjmqj 2016-12-19
  • 打赏
  • 举报
回复
pthread_cond_wait是阻塞的,而且已经用了锁,外面再加个锁是多余的,把四句pthread_mutex_xxxx去掉就可以了

23,217

社区成员

发帖
与我相关
我的任务
社区描述
Linux/Unix社区 应用程序开发区
社区管理员
  • 应用程序开发区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧