现要让四个文件呈如下格式:
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....
请设计程序。
下面举例A,对于B、C、D只是需要把修改一下全局变量n的初始化值即可:
#include <iostream>
#include <stdlib.h>
#include <pthread.h>
using namespace std; pthread_mutex_t myloack=PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t mycond=PTHREAD_COND_INITIALIZER;
int n=;
void *ThreadFunc(void *arg)
{
int num=(int )arg;
for (int i = ; i < ; ++i)
{
pthread_mutex_lock(&myloack);
while (n!=num)
pthread_cond_wait(&mycond,&myloack); if (num==)
cout<<"";
else if(num==)
cout<<"";
else if(num==)
cout<<"";
else
cout<<""<<endl;
n=(n+)%;
pthread_mutex_unlock(&myloack);
pthread_cond_broadcast(&mycond);
}
return (void *);
} int main(int argc, char const *argv[])
{ pthread_t id[];
for (int i = ; i < ; ++i)
{
int err=pthread_create(&id[i],NULL,ThreadFunc,(void *)i);
if (err!=)
{
cout<<"create err:"<<endl;
exit(-);
} } for (int i = ; i < ; ++i)
{
int ret=pthread_join(id[i],NULL);
if (ret!=)
{
cout<<"join err:"<<endl;
exit(-);
}
}
return ;
}