嵌入式学习——进线程(互斥锁和同步)——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;
}
相关推荐
菜鸟~noob2336 分钟前
【电子战】第15篇:混合定位——TDOA/FDOA/AOA 联合【含matlab代码】
开发语言·matlab
IT小白杨1 小时前
社媒多账号运营的环境隔离:一张图谱模型,解释清“为什么换IP还是被连坐“
经验分享·笔记·矩阵·指纹浏览器
kyrie_sakura1 小时前
python学习笔记15 -- Anaconda,Jupyter,numpy
python·学习·jupyter·numpy
Dreams_l1 小时前
死信队列和延迟队列介绍
java·开发语言
Zenova EdgeOS2 小时前
Python 工业边缘 redis-py 异步实战
开发语言·redis·python
君顾13 小时前
西安 24 小时自助健身房系统开发实战指南
java·开发语言·健身房
小羊没烦恼!3 小时前
Memory 记忆设计讨论:Agent Memory 的数据模型可以怎么设计
java·开发语言·前端·c++·c#
程序猿编码4 小时前
两张 3090 扛 27B:Qwen3.8-27B 大模型 DFlash2 加速版生产级落地
开发语言·gpt·深度学习·神经网络·大模型·qwen
welfare9624 小时前
新号别搞:内存管理+模板初阶+STL简介
开发语言·c++
PC2005-cloud4 小时前
Rust学习笔记:控制流——if、loop、while、for与match
笔记·学习·rust