【Linux】Semaphore信號量線程同步的例子


 

0、 信號量

Linux下的信號量和windows下的信號量稍有不同。

 

Windows

Windows下的信號量有一個最大值和一個初始值,初始值和最大值可以不同。  而且Windows下的信號量是一個【內核對象】,在整個OS都可以訪問到。

 

Linux

Linux下的信號量在創建的時候可以指定一個初始值,這個初始值也是最大值。 而且Linux下的信號量可以根據需要設置為是否是【進程間共享】的,如果不是進程間共享的則就是一個本進程局部信號量。

 

 1、相關API

int semt_init( semt_t* sem,     //a semaphore pointer
 int     pshared, //0 as a local semaphore of cuurent process, or the semaphore can be shared between mulit processes
 unsigned value   //the init value of this memaphore
 ) //minus ONE value of semaphore
int sem_wait(sem_t* sem); //add ONE value of semaphore
int sem_post(sem_t* sem); //destroy the semaphore
int sem_destroy(sem_t* sem); All the functions above Rerurn ZERO IF SUCCESS !

 

 

 

 

2、上代碼

 這個demo創建了5個線程,信號量的初始值為2,即同時最多有2個線程可以獲得獲得信號量從而得到執行。

#include <iostream> #include <pthread.h> #include <unistd.h> #include <semaphore.h>
using namespace std; sem_t g_semt; void* work_thread(void* p) { pthread_t tID = pthread_self(); cout << "-------" << tID << " is waiting for a semaphore -------" << endl; sem_wait(&g_semt); cout << "-------" << tID << " got a semaphore, is Runing -------" << endl << endl; usleep(1000 * 1000 * 2);  //2 seconds
    sem_post(&g_semt); static char* pRet = "thread finished! \n"; return pRet; } int main() { const size_t nThreadCount = 5; //amounts of thread array
    const unsigned int nSemaphoreCount = 2; //initial value of semaphore
    int nRet = -1; void* pRet = NULL; pthread_t threadIDs[nThreadCount] = {0}; nRet = sem_init(&g_semt, 0, nSemaphoreCount); if (0 != nRet) return -1; for (size_t i = 0; i < nThreadCount; ++ i) { nRet = pthread_create(&threadIDs[i], NULL, work_thread, NULL); if (0 != nRet) continue; } for (size_t i = 0; i < nThreadCount; ++ i) { int nRet2 = pthread_join(threadIDs[i], &pRet); cout << endl << threadIDs[i] << " return value is " << (char*)pRet << endl; } cout << endl << endl; sem_destroy(&g_semt); return 0; }

 

 

 

   

 

 

4、執行情況

 編譯 g++ -D_REENTRANT  -lpthread   semaphore.cpp  -g  -o  semaphore.out

 

 

 

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM