1. 头文件
#include<semaphore.h>
2. 类型
2.1. 类型值
sem_t semTest;
3. 接口
3.1. 信号量接口
3.1.1 动态初始化资源
int sem_init (sem_t *__sem, int __pshared, unsigned int __value);
3.1.2. 动态释放资源
int sem_destroy (sem_t *__sem);
3.1.3. 信号量锁定
int sem_wait (sem_t *__sem);
3.1.4. 带超时时间的信号量锁定
struct timespec
{
__time_t tv_sec;
long int tv_nsec;
};
int sem_timedwait (sem_t *__sem, const struct timespec *__abstime);
3.1.5. 不阻塞信号量锁定
int sem_trywait (sem_t *__sem);
3.1.6. 信号量解锁
int sem_post (sem_t *__sem);
3.1.6. 获取当前信号量的值
int sem_getvalue (sem_t * __sem, int * __sval);
4. 示例
4.1. 信号量示例
##include <iostream>
#include <pthread.h>
#include <semaphore.h>
#include <unistd.h>
sem_t g_sem;
static void* semWaitThread(void *arg)
{
std::cout << "enter semWaitThread " << pthread_self() << " ." << std::endl;
sem_wait(&g_sem);
int iValue = 0;
sem_getvalue(&g_sem, &iValue);
std::cout << "thread id is " << pthread_self() << ", sem value is " << iValue << std::endl;
std::cout << "semWaitThread continue " << pthread_self() << " ." << std::endl;
return nullptr;
}
static void* semPostThread(void *arg)
{
std::cout << "enter semPostThread " << pthread_self() << " ." << std::endl;
sem_post(&g_sem);
int iValue = 0;
sem_getvalue(&g_sem, &iValue);
std::cout << "thread id is " << pthread_self() << ", sem value is " << iValue << std::endl;
std::cout << "semPostThread continue " << pthread_self() << " ." << std::endl;
return nullptr;
}
int main()
{
sem_init(&g_sem, 0, 2);
pthread_t semWaitThreadId[3];
for (int i = 0; i < 3; i++)
{
int iValue = i+1;
pthread_create(&semWaitThreadId[i], nullptr, semWaitThread, nullptr);
pthread_detach(semWaitThreadId[i]);
sleep(1);
}
sleep(3);
pthread_t semPostThreadId[3];
for (int i = 0; i < 3; i++)
{
int iValue = i+1;
pthread_create(&semPostThreadId[i], nullptr, semPostThread, nullptr);
pthread_detach(semPostThreadId[i]);
sleep(1);
}
sem_destroy(&g_sem);
return 0;
}
enter semWaitThread 140258284926528 .
thread id is 140258284926528, sem value is 1
semWaitThread continue 140258284926528 .
enter semWaitThread 140258284926528 .
thread id is 140258284926528, sem value is 0
semWaitThread continue 140258284926528 .
enter semWaitThread 140258284926528 . 因为信号量为2所以第三个线程会在此处阻塞。
enter semPostThread 140258276533824 . 此处有一个post操作信号量加1,后续被阻塞的线程获取信号量继续执行。
thread id is 140258276533824, sem value is 1 此时被阻塞的线程继续执行
semPostThread continue 140258276533824 .
thread id is 140258284926528, sem value is 0
semWaitThread continue 140258284926528 .
enter semPostThread 140258284926528 .
thread id is 140258284926528, sem value is 1
semPostThread continue 140258284926528 .
enter semPostThread 140258284926528 .
thread id is 140258284926528, sem value is 2
semPostThread continue 140258284926528 .