Better Ourselves!

A Programmer!

Producer/Consumer Model(pthread)

想用pthread做一个生产者/消费者的模型,这个事情想了很久了,一直都懒得动手,本以为很容易,写起来才知道,自己工作这几年,一直看代码,很少写代码,原来的技术功底就不怎么好,这下基本全废了~


先用pthread随便写了个代码:

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

#include <pthread.h>

pthread_t producer_thread;
pthread_t consumer_thread;

void* producer_routine(void* parg);
void* consumer_routine(void* parg);

int main(int argc, char** argv)
{
    int result = 0;
    
    result = pthread_create(&consumer_thread, NULL, &consumer_routine, NULL);

    printf("result for creating consumer_thread is: %d\n", result);
    
    result = pthread_create(&producer_thread, NULL, &producer_routine, NULL);

    printf("result for creating producer_thread is: %d\n", result);
    
    return 0;
}

void* producer_routine(void* parg)
{
    while(1)
    {
        printf("i am producer thread~\n");


        sleep(2);
    }
}

void* consumer_routine(void* parg)
{
    while(1)
    {
        printf("i am consumer thread~\n");

        sleep(2);
    }
}

程序运行时发现,创建的两个线程,并不是像自己想象的那样,在不停的打印,而是只打印个一两次,甚至有时一次都不打印,程序就终止了,开始还以为系统有什么限制,导致进程被Kill,想来想去才发现,主线程运行结束退出,创建的这两个子线程也就Over了,因此修改了main函数:

int main(int argc, char** argv)
{
    int result = 0;
    
    result = pthread_create(&consumer_thread, NULL, &consumer_routine, NULL);

    printf("result for creating consumer_thread is: %d\n", result);
    
    result = pthread_create(&producer_thread, NULL, &producer_routine, NULL);

    printf("result for creating producer_thread is: %d\n", result);
    
    while(1);

    return 0;
}

加了个“while(1);”,这个功能虽然可以,但是毕竟看着太业余了,再修改一下:

int main(int argc, char** argv)
{
    int result = 0;
    
    result = pthread_create(&consumer_thread, NULL, &consumer_routine, NULL);

    printf("result for creating consumer_thread is: %d\n", result);
    
    result = pthread_create(&producer_thread, NULL, &producer_routine, NULL);

    printf("result for creating producer_thread is: %d\n", result);
    
    pthread_join(consumer_thread, NULL);
    pthread_join(producer_thread, NULL);


    return 0;
}

感觉这样才看着像那么回事~

明天的计划,用 Double Linked List的方式实现Producer/Consumer Model~



阅读更多
版权声明: https://blog.csdn.net/xiruanliuwei/article/details/46810399
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

Producer/Consumer Model(pthread)

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭