嵌入式学习——进线程(互斥锁和同步)——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;
}
相关推荐
天若有情6731 小时前
程序员原创|借鉴JS事件冒泡,根治电脑文件混乱的“冒泡整理法”
开发语言·javascript·windows·ecmascript·电脑·办公·日常
小e说说1 小时前
拯救孩子学习兴趣大作战!这些软件超神了
学习
九成宫1 小时前
Outlook使用
windows·笔记·outlook·办公
特种加菲猫2 小时前
继承,一场跨越时空的对话
开发语言·c++
玩转单片机与嵌入式3 小时前
玩转边缘AI(TInyML):需要掌握的C++知识汇总!
开发语言·c++·人工智能
茉莉玫瑰花茶3 小时前
Qt 信号与槽 [ 1 ]
开发语言·数据库·qt
呱呱巨基4 小时前
Linux 基础IO
linux·c++·笔记·学习
AI人工智能+电脑小能手4 小时前
【大白话说Java面试题】【Java基础篇】第30题:JDK动态代理和CGLIB动态代理有什么区别
java·开发语言·后端·面试·代理模式
张健11564096484 小时前
临界区和同一线程上锁
java·开发语言·jvm