嵌入式学习——进线程(互斥锁和同步)——day26

  1. 两个线程进行售票处理,售票一百张
cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

pthread_mutex_t mutex;
int tick =100;

void * th(void* arg)
{

    while(1)
    {
        pthread_mutex_lock(&mutex);
        if(tick>0)
        {
            printf("%s tick:%d\n", (char*)arg,tick-- );
            pthread_mutex_unlock(&mutex);

            usleep(1000*100);
        }
        else 
        {
            pthread_mutex_unlock(&mutex);
            break;

        }
    }
    return NULL;
}
int main(int argc, char *argv[])
{

    pthread_t tid1,tid2;
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&tid1,NULL,th,"WIN1");
    pthread_create(&tid2,NULL,th,"WIN2");

    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    pthread_mutex_destroy(&mutex);
    return 0;
}
  1. 对资源的获取和释放
cpp 复制代码
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <semaphore.h>
sem_t sem_MEM;
int mem[3]={0};
int get_mem()
{
    sem_wait(&sem_MEM);
    int i = 0 ;
    for(i = 0 ;i<3;i++)
    {
    
        if(0 == mem[i])
        {
            mem[i] = 1;
            break;
        }
    }
    return i;
}
void relese_mem(int id)
{
    mem[id] = 0 ;
    sem_post(&sem_MEM);
}
void* th(void* arg)
{

    int id = get_mem();
    printf("get mem ,tid:%lu ,mem:%d\n" ,pthread_self(),id);
    sleep(rand()%5 +1);
    printf("relese mem,tid:%lu mem:%d\n",pthread_self(),id);
    relese_mem(id);

    return NULL;

}
int main(int argc, char *argv[])
{
    
    int i = 0 ;
    pthread_t tid[10]={0};
    sem_init(&sem_MEM,0,3);
    for(i = 0 ;i<10;i++)
    {
        pthread_create(&tid[i],NULL,th,NULL);
    }

    for(i=0;i<10;i++)
    {
    
        pthread_join(tid[i],NULL);
    }
    sem_destroy(&sem_MEM);
    return 0;
}
相关推荐
C_Liu_3 分钟前
13.C++:继承
开发语言·c++
张人玉5 分钟前
c#串口读写威盟士五插针
开发语言·c#·通讯
路长冬12 分钟前
matlab与数字信号处理的不定期更新
开发语言·matlab·信号处理
Thexhy21 分钟前
在 CentOS 7 的 Linux 系统中配置 NFS
linux·运维·学习·centos
卡卡酷卡BUG29 分钟前
Java 后端面试干货:四大核心模块高频考点深度解析
java·开发语言·面试
Yolo566Q32 分钟前
OpenLCA生命周期评估模型构建与分析
java·开发语言·人工智能
安娜的信息安全说43 分钟前
深入浅出 MQTT:轻量级消息协议在物联网中的应用与实践
开发语言·物联网·mqtt
是Yu欸1 小时前
【博资考5】网安2025
网络·人工智能·经验分享·笔记·网络安全·ai·博资考
在坚持一下我可没意见1 小时前
HTTP 协议基本格式与 Fiddler 抓包工具实战指南
java·开发语言·网络协议·tcp/ip·http·java-ee·fiddler
樱花开了几轉1 小时前
element ui下拉框踩坑
开发语言·javascript·ui