三個線程每個線程輸出一個字符
阿新 • • 發佈:2018-11-24
code color fail read div break creat fine con
#include<stdio.h> #include<unistd.h> #include<pthread.h> #define NUM 3 int n=0; pthread_mutex_t t_mutex; pthread_cond_t t_cond; void *Execute(void *p) { int i=0; int para = (int)p; for(;i<10;i++) { pthread_mutex_lock(&t_mutex); while(para!= n) pthread_cond_wait(&t_cond,&t_mutex); printf("%c ",para +‘A‘); n = (n+1)%NUM; pthread_cond_broadcast(&t_cond); pthread_mutex_unlock(&t_mutex); } return (void *)0; } int main() { int i=0; pthread_t thread[NUM]; for(;i<NUM;i++) { int ret = pthread_create(&thread[i],NULL,Execute,(void * )i); if(ret != 0) { printf("create pthread failed \n"); break; } } for(i=0;i<NUM;i++) { pthread_join(thread[i],NULL); } printf("\nmain thread finished\n"); }
三個線程每個線程輸出一個字符