1:有一个隧道,全长5公里,有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>
pthread_mutex_t train1;
pthread_mutex_t train2;
void* run(void* arg)
{
while(1)
{
pthread_mutex_lock(&train2);
printf("train2 is moving in the tunel\n");
usleep(1000000);
printf("train2 has already passed through the tunnel\n");
pthread_mutex_unlock(&train2);
}
}
int main(int argc, const char *argv[])
{
pthread_t id;
pthread_create(&id,0,run,0);
pthread_mutex_init(&train1,0);
pthread_mutex_init(&train2,0);
pthread_detach(id);
while(1)
{
pthread_mutex_lock(&train1);
printf("train1 is moving in the tunel\n");
usleep(5000000);
printf("train1 has already passed through the tunnel\n");
pthread_mutex_unlock(&train1);
}
return 0;
}