一个线程和互斥的例子

来源:互联网 发布:养成游戏 知乎 编辑:程序博客网 时间:2024/05/18 03:30

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

//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\n",i );            pthread_mutex_unlock(&mutex);//离开互斥区    }}/******************************************************函数名:void *consumer(void *arg)参数:功能:消费者函数,在互斥区里使变量i减少*******************************************************/void *consumer(void *arg){    while(running)//没有设置退出时    {            pthread_mutex_lock(&mutex);//进入互斥区            i--;//计数值减少            printf("消费者:当前总数量:%d\n",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

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

0 0