Linux C 多執行緒程式設計互斥鎖與條件變數

2021-09-26 06:31:00 字數 1232 閱讀 5719

linux c 多執行緒程式設計互斥鎖與條件變數

#include"mylib.h"

#define buffer_size 5 //產品庫存大小

#define product_cnt 30 //產品生產總數

struct product_cons

buffer;

void init(struct product_cons *p)

void finish(struct product_cons *p)

//儲存乙個資料到buffer

void put(struct product_cons *p,int data)//輸入產品子函式

p->buffer[p->writepos] = data;

p->writepos ++;

if(p->writepos >= buffer_size)

p->writepos = 0;

pthread_cond_signal(&p->notempty);

pthread_mutex_unlock(&p->lock);

}//讀,移除乙個資料 從buffer

int get(struct product_cons *p)

data = p->buffer[p->readpos];

p->readpos++;

if(p->readpos >= buffer_size)

p->readpos = 0;

pthread_cond_signal(&p->notefull);

pthread_mutex_unlock(&p->lock);

return data;

}void *producer(void *data)//子執行緒,生產

printf("producer stopped\n");

return null;

}void *consumer(void *data)

printf("consumer stopped\n");

return null;

}int main(int argc,char * ar**)

實驗結果:

linux c 多執行緒互斥鎖

beers.c include include include include include include int beers 2000000 建立互斥鎖,互斥鎖對所有可能發生衝突的執行緒可見,是乙個全域性變數.pthread mutex initializer實際上是乙個巨集,當編譯器看到它,...

多執行緒程式設計 互斥鎖

多執行緒程式設計 互斥鎖 1 引言 互斥鎖,是一種訊號量,常用來防止兩個程序或執行緒在同一時刻訪問相同的共享資源。可以保證以下三點 1 原子性 把乙個互斥量鎖定為乙個原子操作,這意味著作業系統 或pthread函式庫 保證了如果乙個執行緒鎖定了乙個互斥量,沒有其他執行緒在同一時間可以成功鎖定這個互斥...

Linux多執行緒程式設計 執行緒互斥鎖

通過下面的練習加深對執行緒的概念的理解,同時明確執行緒的控制。從而進一步了解執行緒的互斥,並學會利用pthread庫。定義乙個用於互斥的互斥鎖 和乙個主函式和兩個子執行緒都能訪問的共享變數,乙個主函式和兩個用來建立子執行緒的子函式 在主函式中定義兩個子執行緒id的變數,初始化互斥鎖,建立對應函式的子...