利用线程解决生产者——消费者问题

来源:互联网 发布:nginx 域名 需要申请吗 编辑:程序博客网 时间:2024/05/16 12:32

ubuntu 下qt creator 比 codeblocks 更好用。然而vs比qt creator 好用很多,可是win不支持pthread.h。qt creator缺点是要配置一下才能输入中文。谷歌一下就行。超级无敌爽。至于vim,应该是ide装vim插件,利用vim的普通模式,而不是vim装ide打功能。。。vim有时编译不好,像多线程链接就要加上pthread,用vim的话没用工程配置的概念。


#include<pthread.h>#include<stdio.h>#include<stdlib.h>#define MAX 1000pthread_mutex_t the_mutex;//互斥量pthread_cond_t condc,condp;//条件变量int buffer=0;//缓冲内容void *producer(void *ptr){       for(int i=1;i<=MAX;i++)    {        pthread_mutex_lock(&the_mutex);//互斥使用缓冲区        while(buffer!=0)        {            pthread_cond_wait(&condp,&the_mutex);//阻塞以等待信号        }        buffer=i;        printf("producer %d\n",i);        pthread_cond_signal(&condc);//向另一个进程发出信号唤醒        pthread_mutex_unlock(&the_mutex);//释放缓冲区    }    pthread_exit(0);}void *consumer(void *ptr){    int i;    for(i=1;i<=MAX;i++)    {        pthread_mutex_lock(&the_mutex);        while(buffer==0)            pthread_cond_wait(&condc,&the_mutex);        printf("consumer %d\n",buffer);        buffer=0;        pthread_cond_signal(&condp);        pthread_mutex_unlock(&the_mutex);    }    pthread_exit(0);}int main(){    pthread_t pro,con;//线程号    pthread_mutex_init(&the_mutex,0);//创建一个互斥变量    pthread_cond_init(&condc,0);//创建一个条件变量    pthread_cond_init(&condp,0);    pthread_create(&con,0,consumer,NULL);//创建线程    pthread_create(&pro,0,producer,NULL);    pthread_join(pro,0);//如果没有pthread_join;主线程会很快结束从而使整个进程结束,从而使创建的线程没有机会开始执行就结束了    pthread_join(con,0);//加入pthread_join后,主线程会一直等待直到等待的线程结束自己才结束,使创建的线程有机会执行    //pthread_join函数会让主线程阻塞,直到所有线程都已经退出    pthread_cond_destroy(&condc);//销毁条件变量    pthread_cond_destroy(&condp);    pthread_mutex_destroy(&the_mutex);//销毁互斥变量}


0 0
原创粉丝点击