1.2⒉编写一个程序,开启3个线程,这3个线程的ID分别为ABC,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示,如ABCABC....….依次递推
void* printA(void* arg){
int i=0;
while(i<10){
pthread_mutex_lock(&mutex);
if(flag!=0){
pthread_cond_wait(&cond1,&mutex);
}
printf("A-%d--%ld\n",i+1,pthread_self());
flag=1;
pthread_cond_signal(&cond2);
i++;
pthread_mutex_unlock(&mutex);
}
}
void* printB(void* arg){
int i=0;
while(i<10){
pthread_mutex_lock(&mutex);
if(flag!=1){
pthread_cond_wait(&cond2,&mutex);
}
printf("B-%d--%ld\n",i+1,pthread_self());
flag=2;
pthread_cond_signal(&cond3);
i++;
pthread_mutex_unlock(&mutex);
}
}
void* printC(void* arg){
int i=0;
while(i<10){
pthread_mutex_lock(&mutex);
if(flag!=2){
pthread_cond_wait(&cond3,&mutex);
}
printf("C-%d--%ld\n",i+1,pthread_self());
flag=0;
pthread_cond_signal(&cond1);
i++;
pthread_mutex_unlock(&mutex);
}
}
void ABCprint(){
pthread_t A;
pthread_t B;
pthread_t C;
if(pthread_create(&A,NULL,printA,NULL)!=0){
perror("pthread_create");
return;
}
if(pthread_create(&B,NULL,printB,NULL)!=0){
perror("pthread_create");
return;
}
if(pthread_create(&C,NULL,printC,NULL)!=0){
perror("pthread_create");
return;
}
pthread_join(A,NULL);
pthread_join(B,NULL);
pthread_join(C,NULL);
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&cond1);
pthread_cond_destroy(&cond2);
pthread_cond_destroy(&cond3);
}
2.创建父子进程,实现父子进程的通话。 1)父进程先发送一句话给子进程,子进程接收打印。 2)子进程发送与句话给父进程,父进程接收后打印。 3)重复1)2)步骤即可。 4)当父进程或者子进程发送quit后,父子进程均要结束。
void test_pipe(){
int ptd1[2];
int ptd2[2];
int flag=0;
if(pipe(ptd1)<0){
perror("pipe");
return;
}
if(pipe(ptd2)<0){
perror("pipe");
return;
}
pid_t pid=fork();
if(pid>0){
char buf[20];
while(strcmp("quit",buf)!=0){
bzero(buf,sizeof(buf));
printf("父进程给子进程发消息:\n");
scanf("%s",buf);
write(ptd1[1],buf,sizeof(buf));
read(ptd2[0],buf,sizeof(buf));
printf("父进程接收到消息:%s\n",buf);
}
}else if(pid==0){
char buf[20];
while(1){
read(ptd1[0],buf,sizeof(buf));
if(strcmp("quit",buf)==0){
break;
}
printf("子进程接收到消息:%s\n",buf);
bzero(buf,sizeof(buf));
printf("子进程给父进程发消息:\n");
scanf("%s",buf);
write(ptd2[1],buf,sizeof(buf));
if(strcmp("quit",buf)==0){
exit(0);
}
}
write(ptd2[1],"quit",4);
exit(0);
}else{
perror("fork");
return;
}
wait(NULL);
}