当前位置: 技术问答>linux和unix
Linux多线程菜鸟求助
来源: 互联网 发布时间:2017-05-29
本文导语: 本帖最后由 download_cs 于 2014-09-18 09:58:11 编辑 #include #include #include pthread_mutex_t counter_lock; pthread_cond_t counter_nonzero; int estatus = -1; int tickets = 100; void *decrement_counter(void *argv); void *increment_counter(void *argv); int...
#include
#include
pthread_mutex_t counter_lock;
pthread_cond_t counter_nonzero;
int estatus = -1;
int tickets = 100;
void *decrement_counter(void *argv);
void *increment_counter(void *argv);
int main(int argc, char **argv)
{
pthread_t thd1, thd2;
int ret;
ret = pthread_create(&thd1, NULL, decrement_counter, NULL);
if(ret){
perror("del:n");
return 1;
}
ret = pthread_create(&thd2, NULL, increment_counter, NULL);
if(ret){
perror("inc:n");
return 1;
}
sleep(10);
return 0;
}
void *decrement_counter(void *argv)
{
while(1)
{
pthread_mutex_lock(&counter_lock);
if(tickets > 0)
{
// usleep(100);
printf("Thread1 sell ticket:%dn",tickets);
tickets--;
}
else
break;
pthread_cond_wait(&counter_nonzero, &counter_lock); //进入阻塞(wait),等待激活(signal)
pthread_mutex_unlock(&counter_lock);
}
return &estatus;
}
void *increment_counter(void *argv)
{
while(1)
{
pthread_mutex_lock(&counter_lock);
if(tickets > 0)
{
// usleep(100);
printf("Thread2 sell ticket:%dn",tickets);
tickets--;
}
else
break;
pthread_cond_signal(&counter_nonzero); //激活(signal)阻塞(wait)的线程(先执行完signal线程,然后再执行wait线程)
pthread_mutex_unlock(&counter_lock);
}
return &estatus;
}
程序代码如上,输出结果列出如下:为什么不是线程1和2交替运行呢?大部分是线程2在运行,求大神指点,还是我对多线程理解有问题?
|
pthread_cond_signal(&counter_nonzero); //激活(signal)阻塞(wait)的线程(先执行完signal线程,然后再执行wait线程)
pthread_mutex_unlock(&counter_lock);
sleep(2) //Add a sleep here and try again
ur code doesn't give thread 1 time to take over.
P.S., Sleep is not a very robust way to serialize threads
pthread_mutex_unlock(&counter_lock);
sleep(2) //Add a sleep here and try again
ur code doesn't give thread 1 time to take over.
P.S., Sleep is not a very robust way to serialize threads
|
break之后没有释放锁
|
延时的作用就是当你这个线程运行完之后 不能让该线程再有时间继续占用互斥锁 另外还应该注意线程的释放 你既然都创建线程了 应该想到用完要去释放它咯 好好学吧 像进程线程IO多路复用都是很常用的东西 其实多练练就行了 没有那么难