zoukankan      html  css  js  c++  java
  • 一个线程和互斥的例子

    主函数建立两个线程,生产者和消费者,生产者使变量递增,消费者使变量递减。建立互斥区

    //start from the very beginning,and to create greatness
    //@author: Chuangwei Lin
    //@E-mail:979951191@qq.com
    //@brief: 一个线程和互斥的例子
    
    #include <stdio.h>
    #include <pthread.h>//线程的头文件
    #include <sched.h>
    void *producter(void *arg);//生产者
    void *consumer(void *arg);//消费者
    int i;//缓冲区的计数值
    pthread_mutex_t mutex;//互斥区变量
    int running = 1;//线程运行控制
    /******************************************************
    函数名:main函数
    参数:
    功能:多线程,互斥
    *******************************************************/
    int main(int argc, char const *argv[])
    {
        pthread_t producter_t;//生产者线程控制
        pthread_t consumer_t;//消费者线程控制
        pthread_mutex_init(&mutex,NULL);//初始化互斥
        pthread_create(&producter_t,NULL,(void*)producter,NULL);//建立生产者线程
        pthread_create(&consumer_t,NULL,(void*)consumer,NULL);//建立消费者线程
        usleep(1);//等待线程创建完毕
    
        running = 0;//设置线程退出值
        pthread_join(producter_t,NULL);//等待生产者线程退出
        pthread_join(consumer_t,NULL);//等待消费者线程退出
        pthread_mutex_destroy(&mutex);//销毁互斥
    
        return 0;
    }
    /******************************************************
    函数名:void *producter(void *arg)
    参数:
    功能:生产者函数,在互斥区里使变量i增加
    *******************************************************/
    void *producter(void *arg)
    {
        while(running)//没有设置退出时
        {
                pthread_mutex_lock(&mutex);//进入互斥区
                i++;//计数值增加
                printf("生产者:当前总数量:%d
    ",i );
                pthread_mutex_unlock(&mutex);//离开互斥区
        }
    }
    /******************************************************
    函数名:void *consumer(void *arg)
    参数:
    功能:消费者函数,在互斥区里使变量i减少
    *******************************************************/
    void *consumer(void *arg)
    {
        while(running)//没有设置退出时
        {
                pthread_mutex_lock(&mutex);//进入互斥区
                i--;//计数值减少
                printf("消费者:当前总数量:%d
    ",i );
                pthread_mutex_unlock(&mutex);//离开互斥区
        }
    }

    用命令gcc -o mutex mutex.c -lpthread进行编译,pthread使线程函数的链接库
    运行结果如下:

    [scut_lcw@localhost lcw20150804]$ ./mutex
    生产者:当前总数量:1
    生产者:当前总数量:2
    生产者:当前总数量:3
    生产者:当前总数量:4
    生产者:当前总数量:5
    生产者:当前总数量:6
    生产者:当前总数量:7
    生产者:当前总数量:8
    生产者:当前总数量:9
    消费者:当前总数量:8

    而且每次运行的结果都不大一样,体现了进程之间的竞争。

  • 相关阅读:
    小程序对于华为Oppo的canvas二维码渲染数据量大
    SonarQube代码质量管理工具的升级(sonarqube6.2 + sonar-scanner-2.8 + MySQL5.6+)
    SonarQube代码质量管理工具安装与使用(sonarqube5.1.2 + sonar-runner-dist-2.4 + MySQL5.x)
    在try-catch机制优化IO流关闭时,OutputStreamWriter 数据流被截断
    Java中日期格式化SimpleDateFormat类包含时区的处理方法
    彻底删除mysql服务(清理注册表)
    PHP7新特性的介绍
    RESTful架构详解
    php-config 介绍
    用 phpize 编译共享 PECL 扩展库
  • 原文地址:https://www.cnblogs.com/sigma0-/p/12630530.html
Copyright © 2011-2022 走看看