Linux多線程之同步2 —— 生產者消費者模型,linux多線程

來源:互聯網
上載者:User

Linux多線程之同步2 —— 生產者消費者模型,linux多線程
思路

生產者和消費者(互斥與同步)。資源用隊列類比(要上鎖,一個時間只能有一個線程操作隊列)。

m個生產者。拿到鎖,且產品不滿,才能生產。當產品滿,則等待,等待消費者喚醒。當產品由空到不空,通知消費者。
n個消費者。拿到鎖,且有產品,才能消費。當產品空,則等待,等待生產者喚醒。當產品由滿到不滿,通知生產者。
   
生產者條件:隊列不滿
消費者條件:隊列不空
因此有兩個條件變數。

代碼
/*************************************************************************  > File Name: main.c  > Author: KrisChou  > Mail:zhoujx0219@163.com  > Created Time: Tue 26 Aug 2014 02:55:01 PM CST ************************************************************************/#include <stdio.h>#include <stdlib.h>#include <string.h>#include <pthread.h>#include <unistd.h>#define CNT 20           /* 最多生產20個產品 *//* 用隊列類比車間 *//* front和tail初始化均為0,tail是下一個資源產生的下一個數組空間下標 */typedef struct tag{    int s_arr[CNT + 1] ;   /* 生產20個產品,必須有21個空間,因為如果空間都裝滿產品,無法區別隊列滿和隊列空 */    int s_front ;    int s_tail ;}QUEUE,*pQUEUE ;QUEUE my_que ;/* 資源為空白 */int que_empty(pQUEUE pq){    return pq ->s_front == pq -> s_tail ;}/* 資源為滿 */int que_full(pQUEUE pq){    return  (pq -> s_tail + 1)% (CNT+1) == pq -> s_front ;}int que_cnt(pQUEUE pq){    return (pq -> s_tail  - pq ->s_front + CNT + 1)% (CNT + 1) ;}pthread_mutex_t  mutex ;pthread_cond_t cond_pro, cond_con ;void* pro_handler(void* arg){    pthread_detach(pthread_self());    while(1)    {        pthread_mutex_lock(&mutex) ;        while(que_full(&my_que))        {            pthread_cond_wait(&cond_pro, &mutex);        }        my_que.s_arr[my_que.s_tail ] = rand() % 1000 ;        my_que.s_tail  = (my_que.s_tail + 1)% (CNT + 1) ;        if(que_cnt(&my_que) == 1)        {            pthread_cond_broadcast(&cond_con);        }        printf("produce a product, total num : %d \n", que_cnt(&my_que));        pthread_mutex_unlock(&mutex);        sleep(rand()%3 + 1);    }}void* con_handler(void* arg){    pthread_detach(pthread_self());    while(1)    {        pthread_mutex_lock(&mutex);        while(que_empty(&my_que))        {            pthread_cond_wait(&cond_con, &mutex);        }        my_que.s_front = (my_que.s_front + 1) % (CNT + 1) ;        if(que_cnt(&my_que) == CNT - 1)        {            /*由於我們的主線程是等消費者線程建立完之後,再建立生產者線程,              因此一開始所有消費者線程都會掛起,在條件變數cond_pro的隊列裡排隊              因此需要用broadcast通知所有消費者線程。              不然一次就通知一個生產者線程,就此消費者線程會搶鎖。              當然,如果一開始主線程先建立生產者線程,再建立消費者線程,              由於生產者線程不會全部阻塞,因此可以使用signal來喚醒一個        */            pthread_cond_broadcast(&cond_pro);        }        printf("consume a product, total num: %d \n", que_cnt(&my_que));        pthread_mutex_unlock(&mutex);        sleep(rand()%3 + 1);    }}int main(int argc, char* argv[])//exe pro_num  con_num{    int con_cnt , pro_cnt ;    my_que.s_front = 0 ;     my_que.s_tail = 0 ;    pro_cnt = atoi(argv[1]) ;    con_cnt = atoi(argv[2]) ;    srand(getpid());    pthread_mutex_init(&mutex, NULL);    pthread_cond_init(&cond_pro, NULL);    pthread_cond_init(&cond_con, NULL);    pthread_t* arr = (pthread_t*)calloc(con_cnt + pro_cnt, sizeof(pthread_t));    int index = 0 ;    while(con_cnt > 0)    {        pthread_create(arr + index , NULL, con_handler, NULL);        index ++ ;        con_cnt -- ;    }    sleep(5);    while(pro_cnt > 0)    {        pthread_create(arr + index , NULL, pro_handler, NULL);        index ++ ;        pro_cnt -- ;    }    while(1) ;    pthread_mutex_destroy(&mutex);    pthread_cond_destroy(&cond_pro);    pthread_cond_destroy(&cond_con);    return 0 ;}
 Makefile
main:main.c    gcc -o $@ $< -lpthread

linux下用多線程同步方法解決生產者-消費者問題

...........
你去搜下吧,這種是OS的經典題目,網上多的是源碼。。。。
 
以生產者消費者模型為依據,提供一個多線程生產者-消費者執行個體,用VC或java實現,並具備以下

製片人:時存在的產品的時候,
消費者生產的產品是不夠的:消費類產品
關鍵:當產品到達上限,停止生產,通知消費者的消費
關鍵2:當達到下限,停止消費,並通知生產者生產
共用資料:

代碼
進口的java.util.ArrayList;
BR />公用類ProducerAndConsumer {
ArrayList的產品=新的ArrayList ();
MAX = 10;
布爾取消;

同步失效產生(){
int的大小= products.size();
(大小<MAX){
products.add(大小+“”);
} {
notifyAll()的;
}
}

同步的無效消耗(){
(products.isEmpty()){
嘗試{
的wait();
}(InterruptedException的E){
e.printStackTrace();
}
}
System.out.println( “消費products.remove:”+(0));
}

私人類生產擴充Thread {
@覆蓋
公用無效的run(){...... />(取消){
農產品();
}
}
}

私人階層的消費擴充Thread {
@覆蓋
公用無效的run(){
(取消){
消耗();
}
}
}
/>無效取消(){
取消= TRUE;
}

的公用ProducerAndConsumer(){
新的消費者()。開始();
新的的監製()。開始();}

公用靜態無效的主要(字串[] ARGS){
新ProducerAndConsumer();
}

}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.