嵌入式学习——进线程(互斥锁和同步)——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;
}
相关推荐
Tony Bai2 小时前
高并发后端:坚守 Go,还是拥抱 Rust?
开发语言·后端·golang·rust
li星野2 小时前
打工人日报#20251231
笔记
孙严Pay3 小时前
分享三种不同的支付体验,各自有着不同的特点与适用场景。
笔记·科技·计算机网络·其他·微信
wjs20243 小时前
Swift 类型转换
开发语言
秃了也弱了。3 小时前
python实现定时任务:schedule库、APScheduler库
开发语言·python
YJlio3 小时前
VolumeID 学习笔记(13.10):卷序列号修改与资产标识管理实战
windows·笔记·学习
weixin_440730503 小时前
java数组整理笔记
java·开发语言·笔记
小龙3 小时前
【学习笔记】多标签交叉熵损失的原理
笔记·学习·多标签交叉熵损失
Thera7773 小时前
状态机(State Machine)详解:原理、优缺点与 C++ 实战示例
开发语言·c++
知识分享小能手4 小时前
Ubuntu入门学习教程,从入门到精通,Ubuntu 22.04的Linux网络配置(14)
linux·学习·ubuntu