线程进程-数据调用

文章描述了使用C语言中的多线程和互斥锁实现两个或三个火车模拟通过长度不同的隧道的场景,强调了线程间的同步与临界资源的管理,确保火车按照指定速度顺序通过。
摘要由CSDN通过智能技术生成

1:有一个隧道,全长5公里,有2列火车,全长200米, 火车A时速 100公里每小时 火车B时速 50公里每小时 现在要求模拟火车反复通过隧道的场景(不可能2列火车都在隧道内运行)

2:1:有一个隧道,全长5公里,有3列火车,全长200米, 火车A时速 100公里每小时 火车B时速 50公里每小时 火车c时速 25公里每小时 现在要求 火车A先通过隧道,火车B再通过隧道,最后火车C通过隧道

火车是线程,隧道是临界资源

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t m;
pthread_mutex_t n;

void * runA(void * arg)
{
    while(1){
    //阻塞
        pthread_mutex_lock(&n);
        printf("火车B通过\n");
        float b = 5 / 50;
        sleep(b);
        pthread_mutex_unlock(&n);
    }

}

int main(int argc, const char *argv[])
{
    
    pthread_t id;
    pthread_create(&id,NULL,runA,NULL);
    pthread_detach(id);

    //pthread_mutex_lock(&n);

    while(1){
        pthread_mutex_lock(&m);
        printf("火车A通过\n");
        float a = 5 / 100;
        sleep(a);
        pthread_mutex_unlock(&m);

    }

    return 0;
}
2.第二题

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t m;
pthread_mutex_t n;
pthread_mutex_t k;

void * runA(void * arg)
{
    while(1){
    pthread_mutex_lock(&n);
    printf("火车B通过\n");
    float b = 5 / 50;
    sleep(b);
    pthread_mutex_unlock(&k);
    }

}

void * runB(void * arg)
{
    while(1){
    pthread_mutex_lock(&k);
    printf("火车C通过\n");
    float c = 5 / 25;
    sleep(c);
    pthread_mutex_unlock(&m);
    }
    
}

int main(int argc, const char *argv[])
{
        
    pthread_t id1;
    pthread_t id2;
    pthread_create(&id1,NULL,runA,NULL);
    pthread_create(&id2,NULL,runB,NULL);
    pthread_detach(id1);
    pthread_detach(id2);

    pthread_mutex_lock(&n);
    pthread_mutex_lock(&k);

    while(1){
        pthread_mutex_lock(&m);
        printf("火车A通过\n");
        float a = 5 / 100;
        sleep(a);
        pthread_mutex_unlock(&n);
    }
    return 0;
}
————————————————

                            版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
                        
原文链接:https://blog.csdn.net/HenryHot/article/details/137480148

  • 5
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值