当前位置: 首页 > article >正文

pthread 使用入门

一、 Pthreads API中的函数可以非正式的划分为三大类:

线程管理: 第一类函数直接用于线程:创建(creating),分离(detaching),连接(joining)等等
互斥量(Mutexes): 第二类函数是用于线程同步的,称为互斥量(mutexes)
条件变量(Condition variables):条件变量是利用线程间共享的全局变量进行同步的一种机制,主要包括两个动作:一个线程等待"条件变量的条件成立"而挂起;另一个线程使"条件成立"(给出条件成立信号)。为了防止竞争,条件变量的使用总是和一个互斥锁结合在一起。

2 例子

2.1、创建/终止线程

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

 void* xc(void* arg){
           char* c=(char*)arg;
           printf("参数%s \n",c);
           int i=0;
        for (;i<10;i++){
                 printf("循环%d\n",i);
                   if(i==5){
                       pthread_exit(1090000000);
               }
      }
             return 100000222;
 }

 void main(){
         
        pthread_t tid;
        pthread_create(&tid,NULL,xc,"线程!!!!");
        void *status;
        pthread_join(tid,&status);
        printf("返回%d\n",(int)status);
}

运行结果
参数线程!!!!
循环0
循环1
循环2
循环3
循环4
循环5
返回1090000000

2.2、线程同步

#include <stdlib.h>                                                         
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
int i = 0;
//互斥锁
pthread_mutex_t mutex;
void* thr_fun(void* arg){
    //加锁
    pthread_mutex_lock(&mutex);
    char* no = (char*)arg;
    for(;i < 5; i++){
        printf("%s thread, i:%d\n",no,i);
        sleep(1);
    }
    i=0;
    //解锁
    pthread_mutex_unlock(&mutex);
}
void main(){
    pthread_t tid1, tid2;
    //初始化互斥锁
    pthread_mutex_init(&mutex,NULL);
    pthread_create(&tid1,NULL,thr_fun,"No1");
    pthread_create(&tid2,NULL,thr_fun,"No2");
    pthread_join(tid1,NULL);
    pthread_join(tid2,NULL);
    //销毁互斥锁
    pthread_mutex_destroy(&mutex);
}

运行结果
No2 thread, i:0
No2 thread, i:1
No2 thread, i:2
No2 thread, i:3
No2 thread, i:4
No1 thread, i:0
No1 thread, i:1
No1 thread, i:2
No1 thread, i:3
No1 thread, i:4

2.3、生产消费者线程

#include <stdlib.h>                                                      
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
//消费者数量
#define CONSUMER_NUM 2
//生产者数量
#define PRODUCER_NUM 1
pthread_t pids[CONSUMER_NUM+PRODUCER_NUM];
//产品队列
int ready = 0;
//互斥锁
pthread_mutex_t mutex;
//条件变量
pthread_cond_t has_product;
//生产
void* producer(void* arg){
    int no = (int)arg;
    //条件变量
    for(;;){
        pthread_mutex_lock(&mutex);
        //往队列中添加产品
        ready++;
        printf("producer %d, produce product\n",no);
        //fflush(NULL);
        //通知消费者,有新的产品可以消费了
        //会阻塞输出
        pthread_cond_signal(&has_product);
        printf("producer %d, singal\n",no);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}
//消费者
void* consumer(void* arg){
    int num = (int)arg;
    for(;;){
        pthread_mutex_lock(&mutex);
        //while?
        //superious wake ‘惊群效应’
        while(ready==0){
            //没有产品,继续等待
            //1.阻塞等待has_product被唤醒
            //2.释放互斥锁,pthread_mutex_unlock
            //3.被唤醒时,解除阻塞,重新申请获得互斥锁pthread_mutex_lock
            printf("%d consumer wait\n",num);
            pthread_cond_wait(&has_product,&mutex);
        }
        //有产品,消费产品
        ready--;
        printf("%d consume product\n",num);
        pthread_mutex_unlock(&mutex);
        sleep(1);
    }
}
void main(){
    //初始化互斥锁和条件变量                                                
    pthread_mutex_init(&mutex,NULL);
    pthread_cond_init(&has_product,NULL);
    printf("init\n");
    int i;
    for(i=0; i<PRODUCER_NUM;i++){
        //生产者线程
        printf("%d\n",i);
        pthread_create(&pids[i],NULL,producer,(void*)i);
    }
    for(i=0; i<CONSUMER_NUM;i++){
        //消费者线程
        pthread_create(&pids[PRODUCER_NUM+i],NULL,consumer,(void*)i);
    }
    //等待
    sleep(10);
    for(i=0; i<PRODUCER_NUM+CONSUMER_NUM;i++){
        pthread_join(pids[i],NULL);
    }
    //销毁互斥锁和条件变量
    pthread_mutex_destroy(&mutex);
    pthread_cond_destroy(&has_product);
}

运行结果
init
0
producer 0, produce product
producer 0, singal
1 consume product
0 consumer wait
producer 0, produce product
producer 0, singal
1 consume product
0 consumer wait
producer 0, produce product
producer 0, singal
1 consume product
0 consumer wait
1 consumer wait
producer 0, produce product
producer 0, singal
0 consume product
producer 0, produce product
producer 0, singal
0 consume product
1 consumer wait
producer 0, produce product
producer 0, singal
0 consume product
1 consumer wait
producer 0, produce product
producer 0, singal
0 consume product
1 consumer wait
0 consumer wait
producer 0, produce product
producer 0, singal
1 consume product
。。。。。


http://www.kler.cn/a/152210.html

相关文章:

  • 【猜数字游戏】用wxPython实现:基本的游戏框架 + 简单的图形用户界面
  • Constraintlayout
  • numpy知识库:深入理解numpy.resize函数和数组的resize方法
  • List系列集合
  • 道路病害检测数据集RDD2022的标签映射关系【参考自官网给出的label_map.pbtxt文件,附查看代码】
  • 华为云cce容器管理中的调度策略作用
  • 在Pycharm中创建项目新环境,安装Pytorch
  • Elasticsearch:对时间序列数据流进行降采样(downsampling)
  • 李宏毅2020机器学习课程笔记(二)- 深度学习
  • 建堆的时间复杂度和堆排序
  • (C++20) constinit常量初始化
  • 显示器校准软件BetterDisplay Pro mac中文版介绍
  • Java微服务框架 HP-SOA 1.0.5 — 完整支持 Spring Cloud 和 Dubbo
  • 常见智力题汇总
  • 游戏反Frida注入检测方案
  • 企业软件的分类|app小程序网站定制开发
  • Linux 命令pwd
  • vue.js ——Vuex
  • K8s 多租户方案的挑战与价值
  • 什么是 Proxy?