【Linux】Semaphore信号量线程同步的例子

 

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

相关文章
相关标签/搜索