日期:2014-05-16 浏览次数:20753 次
#include <stdio.h>
#include <pthread.h>
int count = 0;
pthread_cond_t xx = PTHREAD_COND_INITIALIZER;
pthread_mutex_t mx = PTHREAD_MUTEX_INITIALIZER;
void* a(void* c) {
static int i=0;
while(true) {
pthread_mutex_lock(&mx);
if(i>=30) {
pthread_mutex_unlock(&mx);
break;
}
if(i == (*((int*)c))) pthread_cond_broadcast(&xx);
else pthread_cond_wait(&xx, &mx);
printf("%d\n", i++);
pthread_mutex_unlock(&mx);
}
return NULL;
}
int main()
{
pthread_t x[30];
int ax[30];
for(int i=0; i<30; i++) {
ax[i] = i;
pthread_create(&x[i], NULL, a, &ax[i]);
}
for(int i=0; i<30; i++) pthread_join(x[i], NULL);
return 0;
}