现在有四个文件ABCD。初始都为空。现要让四个文件呈如下格式:
A:1 2 3 4 1 2....
B:2 3 4 1 2 3....
C:3 4 1 2 3 4....
D:4 1 2 3 4 1....
/*threadA.c*/
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define NUM 4
pthread_mutex_t mutex;
pthread_cond_t cond;
int n = 0;
void *thread_func(void *argv)
{
int p = (int)argv;
int i;
for(i = 0; i < 10; i++)
{
pthread_mutex_lock(&mutex);
while(p != n)
{
pthread_cond_wait(&cond,&mutex);
}
printf("%d ",p+1);
n= (n + 1) % NUM;
pthread_mutex_unlock(&mutex);
pthread_cond_broadcast(&cond);
}
}
int main()
{
pthread_t tid[NUM];
int ret;
int i;
pthread_mutex_init(&mutex,NULL);
pthread_cond_init(&cond,NULL);
for(i = 0; i< NUM; i++)
{
ret = pthread_create(&tid[i],NULL,thread_func,(void *)i);
if(ret == -1)
{
printf("pthread_create pid[%d] error!\n",i);
exit(-1);
}
}
for(i = 0; i < NUM; i++)
{
ret = pthread_join(tid[i],NULL);
if(ret == -1)
{
printf("pthread_join pid[%d] error!\n",i);
exit(-1);
}
}
printf("\n");
return 0;
}
B,C,,D文件里分别把全局变量n改为1,2,3。