嵌入式学习——进线程(互斥锁和同步)——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;
}
相关推荐
qq_406176144 分钟前
JavaScript中的循环特点和区别
开发语言·javascript·ecmascript
光通信学徒7 分钟前
爬youtube视频笔记
笔记
我命由我123459 分钟前
Python 开发 - OpenAI 兼容阿里云百炼平台 API
开发语言·人工智能·后端·python·阿里云·ai·语言模型
GokuCode12 分钟前
【GO高级编程】02.GO接收者概述
开发语言·后端·golang
Aotman_14 分钟前
JavaScript去除对象字段空格
开发语言·前端·javascript
云和数据.ChenGuang17 分钟前
Zabbix 6 与 PHP 5 版本**完全不兼容
运维·开发语言·php·zabbix·运维工程师
csbysj202018 分钟前
Ruby 范围(Range)
开发语言
苏 凉23 分钟前
在 openEuler 24.03 LTS SP2 上安装部署 iSula 容器引擎及性能测试
开发语言·rust
qq_3363139334 分钟前
HashMap
java·开发语言