- 论坛徽章:
- 0
|
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
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:%d\n",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:%d\n",tickets);
tickets--;
}
else
break;
pthread_cond_signal(&counter_nonzero); //激活(signal)阻塞(wait)的线程(先执行完signal线程,然后再执行wait线程)
pthread_mutex_unlock(&counter_lock);
}
return &estatus;
}
程序代码如上,输出结果列出如下:为什么不是线程1和2交替运行呢?大部分是线程2在运行,求大神指点,还是我对多线程理解有问题?
|
|