作业:
一:使用无名信号量实现输出春夏秋冬
/*******************************************************/ //=> File Name: season.c //=> Author: Water //=> Mail: 1249496568@qq.com //=> Created Time: 2024年12月16日 星期一 20时44分46秒 /*******************************************************/#include<myhead.h> sem_t sem1,sem2,sem3,sem4; void * spring() {while(1){sem_wait(&sem1);sleep(1);printf("春\n");sem_post(&sem2);} } void * summer() {while(1){sem_wait(&sem2);sleep(1);printf("夏\n");sem_post(&sem3);} } void * autumn() {while(1){sem_wait(&sem3);sleep(1);printf("秋\n");sem_post(&sem4);} } void * winter() {while(1){sem_wait(&sem4);sleep(1);printf("冬\n");sem_post(&sem1);} } int main(int argc, const char *argv[]) {pthread_t tid1,tid2,tid3,tid4;sem_init(&sem1,0,1);sem_init(&sem2,0,0);sem_init(&sem3,0,0);sem_init(&sem4,0,0);if(pthread_create(&tid1,NULL,spring,NULL) == -1){perror("pthread_create");return -1;}if(pthread_create(&tid1,NULL,summer,NULL) == -1){perror("pthread_create");return -1;}if(pthread_create(&tid1,NULL,autumn,NULL) == -1){perror("pthread_create");return -1;}if(pthread_create(&tid1,NULL,winter,NULL) == -1){perror("pthread_create");return -1;}while(1);return 0; }
二:生产者消费者模型使用条件变量实现一遍。
/*******************************************************/ //=> File Name: rolls_royce.c //=> Author: Water //=> Mail: 1249496568@qq.com //=> Created Time: 2024年12月16日 星期一 21时12分45秒 /*******************************************************/#include<myhead.h> pthread_cond_t cond; pthread_mutex_t fastmutex; #define MAX 10 int k = 0; void * producer() {int n = 0;while(n<MAX){sleep(1);printf("生产者%ld生产了%d台劳斯莱斯\n",pthread_self(),++k);n++;pthread_cond_signal(&cond);}pthread_exit(NULL); } void * customer() {pthread_mutex_lock(&fastmutex);pthread_cond_wait(&cond,&fastmutex);printf("消费者%ld消费了1台劳斯莱斯k = %d\n",pthread_self(),k--);pthread_mutex_unlock(&fastmutex);pthread_exit(NULL); } int main(int argc, const char *argv[]) {pthread_t tid1,tid2[MAX];pthread_cond_init(&cond,NULL);pthread_mutex_init(&fastmutex,NULL);if(pthread_create(&tid1,NULL,producer,NULL) == -1){perror("pthread_create");return -1;}for(int i=0;i<MAX;i++){if(pthread_create(&tid2[i],NULL,customer,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; }