线程的问题,可能需要看代码??(new)

自由的风 2004-04-02 10:48:00
pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t mycond;


void *proc(void *arg)
{
while(1)
{
pthread_mutex_lock(&mymutex); //lock
printf("begin ");
pthread_cond_wait(&mycond, &mymutex);
printf("test\n");
pthread_mutex_unlock(&mymutex);
}
}


int main(int argc, char *argv[])
{
pthread_t mythread;
int i;

if ( pthread_create( &mythread, NULL, proc, NULL) )
{
printf("error creating thread.");
abort();
}

pthread_cond_init(&mycond,NULL); //initialize
sleep(1);
for ( i=0; i<20; i++)
{
pthread_cond_broadcast(&mycond);
sleep(1);
}

pthread_cond_destroy(&mycond);
return EXIT_SUCCESS;
}

问题来了:编译通过了,我期望的结果是:先输出"begin" 一秒后接着输出"test",连续20次。但是程序一进入,就阻塞了,没有任何输出,能帮我看看吗?
...全文
61 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
wxywh 2004-04-02
  • 打赏
  • 举报
回复
for ( i=0; i<20; i++)
{
pthread_mutex_lock(&mymutex); //lock
pthread_cond_broadcast(&mycond);
sleep(1);
pthread_mutex_unlock(&mymutex);
}
这样写不会阻塞.
icedust 2004-04-02
  • 打赏
  • 举报
回复
改成这样:
int main(int argc, char *argv[])
{
pthread_t mythread;
int i;

pthread_cond_init(&mycond,NULL); //initialize
sleep(1);
if ( pthread_create(&mythread, NULL, proc, NULL) )
{
printf("error creating thread.");
abort();
}
for ( i=0; i<20; i++)
{
sleep(1);
pthread_cond_broadcast(&mycond);
}

pthread_cond_destroy(&mycond);
return EXIT_SUCCESS;
}

23,127

社区成员

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

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