思维导图
作业
使用无名信号量实现输出春夏秋冬
#include <myhead.h>
sem_t sem1,sem2,sem3,sem4;
void *fun1()
{
while(1)
{
sem_wait(&sem1);
sleep(1);
printf("春\n");
sem_post(&sem2);
}
}
void *fun2()
{
while(1)
{
sem_wait(&sem2);
sleep(1);
printf("夏\n");
sem_post(&sem3);
}
}
void *fun3()
{
while(1)
{
sem_wait(&sem3);
sleep(1);
printf("秋\n");
sem_post(&sem4);
}
}
void *fun4()
{
while(1)
{
sem_wait(&sem4);
sleep(1);
printf("冬\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);
sem_init(&sem4,0,0);
//创建4个子线程
pthread_t tid1,tid2,tid3,tid4;
if(pthread_create(&tid1,NULL,fun1,NULL)==-1)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid2,NULL,fun2,NULL)==-1)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid3,NULL,fun3,NULL)==-1)
{
perror("pthread_create");
return -1;
}
if(pthread_create(&tid4,NULL,fun4,NULL)==-1)
{
perror("pthread_create");
return -1;
}
//等待子线程运行完成
pthread_join(tid1,NULL);
pthread_join(tid2,NULL);
pthread_join(tid3,NULL);
pthread_join(tid4,NULL);
//无名信号量的销毁
sem_destroy(&sem1);
sem_destroy(&sem2);
sem_destroy(&sem3);
sem_destroy(&sem4);
return 0;
}
生产者消费者模型使用条件变量实现一遍。
#include <myhead.h>
#define MAX 10
pthread_cond_t cond;
pthread_mutex_t fastmutex;
int k=0;
void *fun1()
{
for(int i=0;i<MAX;i++)
{
sleep(1);
printf("生产者%ld生产了第%d辆车\n",pthread_self(),++k);
pthread_cond_signal(&cond);
}
pthread_exit(NULL);
}
void *fun2()
{
pthread_mutex_lock(&fastmutex);
pthread_cond_wait(&cond,&fastmutex);
//sleep(1);
printf("消费者%ld消费了一辆车\n",pthread_self());
pthread_mutex_unlock(&fastmutex);
pthread_exit(NULL);
}
int main(int argc, const char *argv[])
{
//初始化条件变量
pthread_cond_init(&cond,NULL);
//初始化互斥锁
pthread_mutex_init(&fastmutex,NULL);
//生产者一个,消费者10个
pthread_t tid1,tid2[MAX];
if(pthread_create(&tid1,NULL,fun1,NULL)==-1)
{
perror("pthread_create");
return -1;
}
for(int i=0;i<MAX;i++)
{
if(pthread_create(&tid2[i],NULL,fun2,NULL)==-1)
{
perror("pthread_create");
return -1;
}
}
//等待子线程完成
pthread_join(tid1,NULL);
for(int i=0;i<MAX;i++)
{
pthread_join(tid2[i],NULL);
}
//销毁互斥锁和条件变量
pthread_mutex_destroy(&fastmutex);
pthread_cond_destroy(&cond);
return 0;
}