多线程信号量PV操作初探
直接上源碼吧:
在主線程中創(chuàng)建一個(gè)信號(hào)量mutex(注意參數(shù),當(dāng)前值和最大值都設(shè)為1),開啟總計(jì)PRODUCER_COUNT份producer線程,不停地對(duì)該信號(hào)量mutex進(jìn)行PV操作;再開啟COMSUNER_COUNT份comsumer線程嘗試獲取信號(hào)量mutex,并打印時(shí)間。
主要用到以下函數(shù):
函數(shù)CreateSemaphore用來創(chuàng)建信號(hào)量,其中第二個(gè)和第三個(gè)參數(shù)表示資源的當(dāng)前值和最大值。
函數(shù)WaitForSingleObject獲取信號(hào)量權(quán)限,使用((ret_code == WAIT_OBJECT_0) || (ret_code == WAIT_ABANDONED))來判斷P操作成功。
函數(shù)ReleaseSemaphore來釋放信號(hào)量。
信號(hào)量的用途在于保證一個(gè)某變量(注意被操作變量,不是信號(hào)量本身,信號(hào)量只是一個(gè)加鎖的標(biāo)志)在同一時(shí)間只被一個(gè)線程編輯,機(jī)上鎖解鎖的功能,確保某變量再多線程間是同步的,不會(huì)發(fā)生沖突。
#include <iostream> #include <windows.h> #include <stdio.h> #define p(s) WaitForSingleObject(s, INFINITE); #define vs(s) ReleaseSemaphore(s,1,NULL); //#define vm(s) ReleaseMutex(s);const int PRODUCER_SLEEP_TIME=100; const int CONSUMER_SLEEP_TIME=100;const int PRODUCER_COUNT=10; const int CONSUMER_COUNT=1;using namespace std;//定義信號(hào)量 HANDLE mutex;//生產(chǎn)者線程 DWORD WINAPI Producer(LPVOID producer) {while(true){int ret_code = p(mutex);if ((ret_code == WAIT_OBJECT_0) || (ret_code == WAIT_ABANDONED)){;//printf("Producer:: P success !\n");}else{printf("Producer:: P fail !!! err_code = %d\n",GetLastError());}Sleep(PRODUCER_SLEEP_TIME);BOOL a=vs(mutex);if (a == TRUE){;//printf("Producer:: V success !\n");;}else{printf("Producer:: V fail !!! err_code = %d\n",GetLastError());}}return 0; } //消費(fèi)者線程 DWORD WINAPI Consumer(LPVOID consumer) { while(true){int ret_code = p(mutex);if ((ret_code == WAIT_OBJECT_0) || (ret_code == WAIT_ABANDONED)){;//printf("Consumer:: P success !\n");;}else{printf("Consumer:: P fail !!! err_code = %d\n",GetLastError());}SYSTEMTIME sys; GetLocalTime( &sys ); printf( "%4d/%02d/%02d %02d:%02d:%02d.%03d 星期%1d\n",sys.wYear,sys.wMonth,sys.wDay,sys.wHour,sys.wMinute,sys.wSecond,sys.wMilliseconds,sys.wDayOfWeek); Sleep(CONSUMER_SLEEP_TIME);BOOL a=vs(mutex);if (a == TRUE){;//printf("Consumer:: V success !\n");;}else{printf("Consumer:: V fail !!! err_code = %d\n",GetLastError());}}return 0; }int main() { //創(chuàng)建信號(hào)量對(duì)象mutex = CreateSemaphore(NULL,1,1,NULL);DWORD producer_id[PRODUCER_COUNT]; //生產(chǎn)者線程的標(biāo)識(shí)符DWORD consumer_id[CONSUMER_COUNT]; //消費(fèi)者線程的標(biāo)識(shí)符 for(int i=0; i<PRODUCER_COUNT; i++){CreateThread(NULL,0,Producer,NULL,0,&producer_id[i]); }//創(chuàng)建消費(fèi)者線程for(int i=0; i<CONSUMER_COUNT; i++){CreateThread(NULL,0,Consumer,NULL,0,&consumer_id[i]);} getchar();getchar(); }總結(jié)
以上是生活随笔為你收集整理的多线程信号量PV操作初探的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 上课时雄安红听到老师提问,就立刻举手回答
- 下一篇: RedHat5 开启telnet,ftp