執行緒之間生產者和消費者模型

2021-07-02 00:52:57 字數 1190 閱讀 8609

#ifndef _cache_h_

#define _cache_h_

#include #include #include #include #include #include #include #include /*傳入的資料型別t構造函式引數應該設定沒有,否則編譯出錯*/

templateclass cachequeue

;templatecachequeue::cachequeue(uint32_t bufsize):_bufsize(bufsize)

templatecachequeue::~cachequeue()

templatevoid cachequeue::push(const t *req)

_requests.push(*req);

pthread_cond_signal(&_not_empty_cond);

// 連續多次呼叫,如果沒有執行緒正在等待該訊號,也是相當於一次

pthread_mutex_unlock(&_mutex);

}templateconst t *cachequeue::pop(int timeout)

if(ret!=0)

t tmp = _requests.front();

memcpy(_req, &tmp, sizeof(t));

_requests.pop();

pthread_cond_signal(&_not_full_cond);

pthread_mutex_unlock(&_mutex);

return _req;

}#endif

#include "cache.h"

class data

void set(int a, int b)

void print() const

private:

int a;

int b;

};cachequeueshare(20);

void *push(void *arg)

pthread_exit(null);

}int main()

else

usleep(100*1000);

}return 0;

}

多執行緒之生產者消費者模型

生產者消費者 乙個最簡單的模型。兩個執行緒,乙個生產者,乙個消費者,生產者負責生產,消費者負責消費。分析 同步 生產者生產了之後,消費者進行讀取資料。wait 和notify機制 互斥 生產者生產時,消費者不能進行讀取。鎖機制。public class producerandconsumer cat...

執行緒,生產者消費者模型

什麼是執行緒 1.執行緒是cpu最小的執行單位 2.程序是資源單位 3.如果將作業系統比作工廠的話,程序是車間,執行緒是流水線,而cpu為電源 開啟乙個程序預設有乙個執行緒即主線程 執行緒的兩種開啟方式 例項化thread類 自定義mythread類,繼承thread類,覆蓋run方法 什麼時候需要...

Java 多執行緒之生產者消費者模型

package com.yuanlief public class main 共享資料類 class mydata 共享資料控制類 class sharedata catch interruptedexception e this.data data writeable false 標記已經生產 n...