有一个隧道,全长5公里(5km),有2列火车,全长200米,火车A时速 100公里每小时,火车B时速 50公里每小时,现在要求模拟火车反复通过隧道的场景(不可能2列火车都在隧道内运行)
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <pthread.h> #include <semaphore.h> #include <wait.h> #include <signal.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/ipc.h> #include <sys/sem.h> #include <semaphore.h> #include <sys/msg.h> #include <sys/shm.h> #include <sys/un.h> sem_t mutex1;//创建信号量 sem_t mutex2;//创建信号量 void* run1(void* arg){ float time1=(5000+200)/(100/3.6); while(1){ sem_wait(&mutex1); printf("火车A正在通过隧道,预计花费%g秒\n",time); sem_post(&mutex2); sleep(1); } return NULL; } void* run2(void* arg){ float time2=(5000+200)/(50/3.6); while(1){ sem_wait(&mutex2); printf("火车B正在通过隧道,预计花费%g秒\n",time2); sem_post(&mutex1); sleep(1); } return NULL; } int main(int argc, const char *argv[]) { pthread_t id1; pthread_t id2; if(pthread_create(&id1,NULL,run1,NULL)!=0){ perror("pthread_create:"); return 1; } if(pthread_create(&id2,NULL,run2,NULL)!=0){ perror("pthread_create:"); return 1; } pthread_detach(id1); pthread_detach(id2); sem_init(&mutex1,0,1); sem_init(&mutex2,0,0); while(1){ } return 0; }
有一个隧道,全长5公里,有3列火车,全长200米, 火车A时速 100公里每小时 火车B时速 50公里每小时 火车c时速 25公里每小时 现在要求 火车A先通过隧道,火车B再通过隧道,最后火车C通过隧道 火车是线程,隧道是临界资源
#include <stdio.h> #include <string.h> #include <unistd.h> #include <stdlib.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <pthread.h> #include <semaphore.h> #include <wait.h> #include <signal.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/socket.h> #include <sys/ipc.h> #include <sys/sem.h> #include <semaphore.h> #include <sys/msg.h> #include <sys/shm.h> #include <sys/un.h> sem_t mutex; sem_t mutex1;//创建信号量 sem_t mutex2;//创建信号量 sem_t mutex3;//创建信号量 void* task_A(void* arg){ float t1=(5000+200)/(100/3.6); while(1){ sem_wait(&mutex1); sem_wait(&mutex); printf("火车A正在通过隧道,预计花费%g秒\n",t1); sem_post(&mutex); sem_post(&mutex2); } return NULL; } void* task_B(void* arg){ float t2=(5000+200)/(50/3.6); while(1){ sem_wait(&mutex2); sem_wait(&mutex); printf("火车B正在通过隧道,预计花费%g秒\n",t2); sem_post(&mutex); sem_post(&mutex2); } return NULL; } void* task_C(void* arg){ float t3=(5000+200)/(25/3.6); while(1){ sem_wait(&mutex3); sem_wait(&mutex); printf("火车C正在通过隧道,预计花费%g秒\n",t3); sem_post(&mutex); sem_post(&mutex1); } return NULL; } int main(int argc, const char *argv[]) { pthread_t id1; pthread_t id2; pthread_t id3; sem_init(&mutex1,0,1); sem_init(&mutex2,0,0); sem_init(&mutex3,0,0); sem_init(&mutex,0,1); if(pthread_create(&id_a,NULL,task_A,NULL)!=0){ perror("pthread_create:"); return 1; } if(pthread_create(&id_b,NULL,task_B,NULL)!=0){ perror("pthread_create:"); return 1; } if(pthread_create(&id_c,NULL,task_C,NULL)!=0){ perror("pthread_create:"); return 1; } pthread_detach(id1); pthread_detach(id2); pthread_detach(id3); while(1){ sleep(1); } return 0; }