1.创建编号为ABC三个线程,三个线程循环打印自己的编号,要求打印出来的结果必须是ABC
代码
#include <stdio.h>
#include <semaphore.h>
#include <pthread.h>
sem_t sem1,sem2,sem3;
void* put_A(void* arg)
{
while(1)
{
sem_wait(&sem1);
printf("A");
sem_post(&sem2);
}
}
void* put_B(void* arg)
{
while(1)
{
sem_wait(&sem2);
printf("B");
sem_post(&sem3);
}
}
void* put_C(void* arg)
{
while(1)
{
sem_wait(&sem3);
printf("c\n");
sem_post(&sem1);
}
}
int main(int argc, const char *argv[])
{
//创建信号灯
sem_init(&sem1,0,1);
sem_init(&sem2,0,0);
sem_init(&sem3,0,0);
//创建子线程
pthread_t tidA,tidB,tidC;
if(pthread_create(&tidA,NULL,put_A,NULL)!=0)
{
fprintf(stderr,"creat pthread on erro\n");
return -1;
}
if(pthread_create(&tidB,NULL,put_B,NULL)!=0)
{
fprintf(stderr,"creat pthread on erro\n");
return -1;
}
if(pthread_create(&tidC,NULL,put_C,NULL)!=0)
{
fprintf(stderr,"creat pthread on erro\n");
return -1;
}
//销毁信号灯
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
//阻塞等待子线程结束
pthread_join(tidA,NULL);
pthread_join(tidB,NULL);
pthread_join(tidC,NULL);
return 0;
}
运行结果
2.无名管道练习
代码(猜测用信号灯实现)
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(int argc, const char *argv[])
{
//创建无名管道
int pfd[2];
if(pipe(pfd)==-1)
{
perror("pipe");
return -1;
}
//创建子进程
pid_t pid=fork();
char buf[128] = "";
if(pid > 0)
{
//父进程
// strcpy(buf,"I'am your father");
// write(pfd[1],buf,sizeof(buf));
read(pfd[0],buf,sizeof(buf));
printf("%s\n",buf);
wait(&pid);
}
else if(pid == 0)
{
//子进程
// read(pfd[0],buf,sizeof(buf));
// printf("%s\n",buf);
strcpy(buf,"I'am your son");
write(pfd[1],buf,sizeof(buf));
}
else
{
perror("fork");
return -1;
}
return 0;
}
运行结果(去掉注释会出现程序阻塞的情况)