0、 信號量ios
Linux下的信號量和windows下的信號量稍有不一樣。windows
Windowspost
Windows下的信號量有一個最大值和一個初始值,初始值和最大值能夠不一樣。 並且Windows下的信號量是一個【內核對象】,在整個OS均可以訪問到。this
Linuxspa
Linux下的信號量在建立的時候能夠指定一個初始值,這個初始值也是最大值。 並且Linux下的信號量能夠根據須要設置爲是不是【進程間共享】的,若是不是進程間共享的則就是一個本進程局部信號量。線程
一、相關APIcode
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 !
二、上代碼對象
這個demo建立了5個線程,信號量的初始值爲2,即同時最多有2個線程能夠得到得到信號量從而獲得執行。blog
#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; }
四、執行狀況進程
編譯 g++ -D_REENTRANT -lpthread semaphore.cpp -g -o semaphore.out