pthread_cond_signal(&cond_l)信号问题

缺心少肺 2017-09-30 12:20:58
原码框架如下
i为全局变量
int main:{
pthread_create(&pid1, NULL, run1, NULL );
printf("new thread:%u\n", (unsigned int)pid1);

pthread_create(&pid2, NULL, run2, NULL );
printf("new thread:%u\n", (unsigned int)pid2);

pthread_create(&pid3, NULL, run3, NULL );
printf("new thread:%u\n", (unsigned int)pid3);

pthread_create(&pid4, NULL, run4, NULL );
printf("new thread:%u\n", (unsigned int)pid4);
sleep(1);
pthread_mutex_lock(&mutex);
i = 6;
pthread_cond_signal(&cond_l);
printf("release signal\n");
pthread_mutex_unlock(&mutex);

}
void* run1(void *s)
{
pthread_mutex_lock(&mutex);
while(i <8 )
{
printf("线程%u进入等待状态\n", (unsigned int)pthread_self());
pthread_cond_wait(&cond_l, &mutex);
printf("1线程%u进入等待状态\n", (unsigned int)pthread_self());
}
printf("已经解开%u\n", (unsigned int)pthread_self());
i = 10;
pthread_cond_signal(&cond_l);
pthread_mutex_unlock(&mutex);

return ((void *) 1);
}
void* run2(void *s)
{
pthread_mutex_lock(&mutex);
while(i < 7 )
{
printf("线程%u进入等待状态\n", (unsigned int)pthread_self());
pthread_cond_wait(&cond_l, &mutex);
printf("2线程%u进入等待状态\n", (unsigned int)pthread_self());
}
printf("已经解开%u\n", (unsigned int)pthread_self());
i = 9;
pthread_cond_signal(&cond_l);
pthread_mutex_unlock(&mutex);

return ((void *) 1);
}

void* run3(void *s)
{
pthread_mutex_lock(&mutex);
while(i < 6)
{
printf("线程%u进入等待状态\n", (unsigned int)pthread_self());
pthread_cond_wait(&cond_l, &mutex);
printf("3线程%u进入等待状态\n", (unsigned int)pthread_self());
}
printf("已经解开%u\n", (unsigned int)pthread_self());
i = 8;
pthread_cond_signal(&cond_l);
pthread_mutex_unlock(&mutex);

return ((void *) 1);
}


void* run4(void *s)
{
pthread_mutex_lock(&mutex);
while(i <5 )
{
printf("线程%u进入等待状态\n", (unsigned int)pthread_self());
pthread_cond_wait(&cond_l, &mutex);
printf("4线程%u进入等待状态\n", (unsigned int)pthread_self());
}
printf("已经解开%u\n", (unsigned int)pthread_self());
i = 7;
pthread_cond_signal(&cond_l);
pthread_mutex_unlock(&mutex);

return ((void *) 1);
}

问题如下:
当主函数修改i的值为6时执行结果如xia:
new thread:3086019472
new thread:3075525520
new thread:3065035664
new thread:3054545808
线程3086019472进入等待状态
线程3075525520进入等待状态
线程3065035664进入等待状态
线程3054545808进入等待状态
release signal
1线程3086019472进入等待状态
线程3086019472进入等待状态
当主函数修改i的值为10时执行结果:
new thread:3085974416
new thread:3075480464
new thread:3064990608
new thread:3054500752
线程3085974416进入等待状态
线程3075480464进入等待状态
线程3064990608进入等待状态
线程3054500752进入等待状态
release signal
1线程3085974416进入等待状态
已经解开3085974416
2线程3075480464进入等待状态
已经解开3075480464
3线程3064990608进入等待状态
已经解开3064990608
4线程3054500752进入等待状态
已经解开3054500752
造成现象的原因是signal优先给run1发信号么?wait函数收到信号不满足条件是丢弃信号,而不会进行转发吗?signal信号的优先级怎么玩的?


...全文
196 回复 打赏 收藏 转发到动态 举报
写回复
用AI写文章
回复
切换为时间正序
请发表友善的回复…
发表回复

23,121

社区成员

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

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