两个线程按顺序打印1~10

来源:互联网 发布:mysql安装步骤 编辑:程序博客网 时间:2024/05/20 23:58
<pre name="code" class="cpp">#include <stdio.h>#include <stdlib.h>#include <pthread.h>#include <unistd.h>pthread_mutex_t lock;pthread_cond_t cond;int i = 1;void* salewinds1(void* args){while(1){pthread_mutex_lock(&lock);if(i == 10){pthread_mutex_unlock(&lock);//退出前解锁否则会造成别的线程死锁pthread_exit(0);}while(i % 2 == 0){pthread_cond_wait(&cond, &lock);}printf("%d\n", i);i += 1;if(i > 10){pthread_mutex_unlock(&lock);pthread_exit(0);}pthread_cond_broadcast(&cond);pthread_mutex_unlock(&lock);}return NULL;}void* salewinds2(void* args){while(1){pthread_mutex_lock(&lock);if(i > 10){pthread_mutex_unlock(&lock);pthread_exit(0);}while(i % 2 == 1){pthread_cond_wait(&cond, &lock);}printf("%d\n", i);i += 1;if(i == 10){pthread_mutex_unlock(&lock);pthread_exit(0);}pthread_cond_broadcast(&cond);pthread_mutex_unlock(&lock);}return NULL;}int main(int argc,const char* argv[]){pthread_t thd1;pthread_t thd2;int val1=1;int val2=2;pthread_mutex_init(&lock, NULL);pthread_cond_init(&cond, NULL);  pthread_create(&thd1, NULL, salewinds1, NULL);pthread_create(&thd2, NULL, salewinds2, NULL);pthread_join(thd1, (void**)&val1);pthread_join(thd2, (void**)&val2);pthread_mutex_destroy(&lock);pthread_cond_destroy(&cond);return 0;}



0 0