Qt 訊號量的執行緒同步

2021-10-03 19:35:07 字數 1496 閱讀 4402

訊號量( semaphore ) 是另一種限制對共享資源進行訪問的執行緒同步機制,它與互斥量 mutex 相似,但是有區別 。乙個互斥量只 能被鎖定一次,而訊號量可 以多次使用 。訊號量通常用來保護一定數量的相同的資源,如資料採集時的雙緩衝區 。

qsemaphore 是實現訊號量功能的類,它提供以下幾個基本 的函式:

讓我們先看圖吧:

有關訊號量,其實跟互斥量乙個意思,只是可以多訊號資源,不只是等到互斥解鎖,直接來上**部分吧。

qmythread.h 標頭檔案

#ifndef qmythread_h

#define qmythread_h

//#include #include //#include class qthreaddaq : public qthread

;class qthreadshow : public qthread

;#endif // qmythread_h

qmythread.cpp

#include    "qmythread.h"

#include //#include const int buffersize = 8;

static int buffer1[buffersize];

static int buffer2[buffersize];

static int curbuf=1; //當前正在寫入的buffer

static int bufno=0; //採集的緩衝區序號

static quint8 counter=0;//資料生成器

static qsemaphore emptybufs(2);//訊號量:空的緩衝區個數,初始資源個數為2

static qsemaphore fullbufs; //滿的緩衝區個數,初始資源為0

qthreaddaq::qthreaddaq()

void qthreaddaq::stopthread()

void qthreaddaq::run()

class dialog : public qdialog

;#endif // dialog_h

對應的cpp檔案:

#ifndef dialog_h

#define dialog_h

#include #include #include "qmythread.h"

namespace ui

class dialog : public qdialog

;#endif // dialog_h

在實際的資料採集中 , 要保證不丟失緩衝區或資料點 ,資料讀取執行緒的速度必須快過資料寫入緩衝區 的執行緒的速度。

qt執行緒同步之訊號量

const int data size 100 const int buf size 10 int buf buf size qmutex mutex 控制線程間的互斥 freespace和usespace控制線程間的同步 控制可被生產者填充資料的那部分緩衝區 qsemaphore freespac...

執行緒訊號量同步

thread sem.c include include include include define thread number 3 define repeat number 3 define delay time levels 10.0 sem t sem thread number void ...

執行緒同步 訊號量

執行緒同步方法 訊號量不常用,找到個帖子不錯,記錄一下!依賴的標頭檔案 include 函式宣告 sem t 表示訊號量 int sem init sem t sem,int pshared,unsigned int value 名稱 sem init 功能 initialize an unname...