- 论坛徽章:
- 0
|
第一:
#include
#include
#include
#include
#include
#include
int count ;
pthread_mutex_t lock;
pthread_cond_t cond;
void *thread1_handle(void *arg)
{
pthread_mutex_lock(&lock);
//count--;
while(count
#include
#include
#include
#include
#include
int count ;
pthread_mutex_t lock;
pthread_cond_t cond;
void *thread1_handle(void *arg)
{
pthread_mutex_lock(&lock);
//count--;
while(count
#include
#include
#include
#include
#include
int count ;
pthread_mutex_t lock;
pthread_cond_t cond;
void *thread1_handle(void *arg)
{
pthread_mutex_lock(&lock);
count--;
while(count
#include
#include
#include
#include
#include
#include
int count ;
pthread_mutex_t lock;
pthread_cond_t cond;
void *thread1_handle(void *arg)
{
pthread_mutex_lock(&lock);
count--;
while(count <= 0)
pthread_cond_wait(&cond,&lock);
printf("in 1st the count value is :%d\n",count);
printf("%s\n",arg);
pthread_mutex_unlock(&lock);
if(pthread_detach(pthread_self()) == 0)
printf("1st thread detached\n");
pthread_exit((void *)1);
}
void *thread2_handle(void *arg)
{
pthread_mutex_lock(&lock);
count += 2;
printf("in 2nd the count value is :%d\n",count);
printf("%s\n",arg);
pthread_cond_signal(&cond);
pthread_mutex_unlock(&lock);
pthread_exit((void *)2);
}
int main(int argc,char **argv)
{
pthread_t tid1,tid2;
int retval;
char buffer1[]="1st thread";
char buffer2[]="2nd thread";
void *p1,*p2;
pthread_mutex_init(&lock,NULL);
pthread_cond_init(&cond,NULL);
retval = pthread_create(&tid2,NULL,(void *)thread2_handle,buffer2);
if(retval != 0)
{
printf("pthread_create error:%s\n",strerror(errno));
exit(errno);
}
retval = pthread_create(&tid1,NULL,(void *)thread1_handle,buffer1);
if(retval != 0)
{
printf("pthread_create error:%s\n",strerror(errno));
exit(errno);
}
retval = pthread_join(tid1,&p1);
if(retval != 0)
{
printf("pthread join error: %s",strerror(errno));
exit(errno);
}
printf("pthread 1st exit code:%d\n",(int)p1);
retval = pthread_join(tid2,&p2);
if(retval != 0)
{
printf("pthread join error:%s\n",strerror(errno));
exit(errno);
}
printf("pthread 2nd exit code :%d\n",(int)p2);
exit(0);
}
结果:
in 2nd the count value is :2
2nd thread
in 1st the count value is :1
1st thread
1st thread detached
pthread 1st exit code:1
pthread 2nd exit code :2
果然是这种竞争造成的后果;
可以
while()
pthread_cond_wait()
count--;
值得注意,线程是公平执行的,当然还得看具体的调度机制
本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/35079/showart_271843.html |
|