- 论坛徽章:
- 0
|
我把全部代码都贴出来算了。。- #include <stdio.h>
- #include <iostream>
- #include <pthread.h>
- using namespace std;
- pthread_mutex_t count_lock;
- pthread_cond_t count_nonzero;
- unsigned count;
- void decrement_count();
- void increment_count();
- void thread1(void)
- {
- cout<<"This is a thread1.\n";
- decrement_count();
- }
- void thread2(void)
- {
- cout<<"This is a thread1.\n";
- increment_count();
- }
- void decrement_count(){
- pthread_mutex_lock (&count_lock);
- while(count==0)
- {
- cout<<"++pthread_cond_wait...\n";
- pthread_cond_wait( &count_nonzero, &count_lock);
- cout<<"--pthread_cond_wait...\n";
- }
- cout<<"退出while循环了.\n";
- count=count -1;
- cout<<__LINE__<<endl;
- pthread_mutex_unlock (&count_lock);
- }
- void increment_count(){
- cout<<__LINE__<<endl;
- pthread_mutex_lock(&count_lock);
- cout<<__LINE__<<endl;
- if(count==0)
- {
- cout<<"++pthread_cond_signal\n";
- pthread_cond_signal(&count_nonzero);
- cout<<"--pthread_cond_signal\n";
- }
- count=count+1;
- cout<<__LINE__<<endl;
- pthread_mutex_unlock(&count_lock);
- }
- int main(void)
- {
- pthread_t id,id2;
- int i,ret;
- count=0;
- pthread_cond_init(&count_nonzero,NULL);
- ret=pthread_create(&id,NULL,(void *(*)(void *))thread1,NULL);
- if(ret!=0){
- cout<<"Create pthread error!\n";
- return (1);
- }
- sleep(1);
- ret=pthread_create(&id2,NULL,(void *(*)(void *))thread2,NULL);
- if(ret!=0){
- cout<<"Create pthread error!\n";
- return (1);
- }
- pthread_join(id,NULL);
- pthread_join(id2,NULL);
- return (0);
- }
复制代码 |
|