简介
POSIX信号量是线程之间同步的机制之一。除此之外,线程的同步机制有互斥量、条件变量。
常用API接口
1.int sem_init(sem_t *sem, int pthread, unsigned int value)
2.int sem_destroy(sem_t *sem)
3.int sem_wait(sem_t sem)
4.int sem_trywait(sem_t * sem)
5.int sem_post(sem_t *sem)
这些函数的第一个参数:sem为指向被操作的信号量。
sem_init:初始化信号量
pthread参数:信号量的类型,值为0,表示当前进程的局部信号量,否则,该信号量可以被多个进程之间共享。
value:指定信号量的初始值。
sem_destroy: 销毁信号量,释放内存。
sem_wait: 以原子的方式将信号量的值减1,当值为0时,函数阻塞。直到这个信号量为非零值。
sem_trywait: 与sem_wait 类似,不过不是阻塞。当信号量为0时,立刻返回-1.并设置errno为EAGAIN。
sem_post :以原子的方式,将信号量加1,当信号量的值大于0时,其他正在调用sem_wait 等待信号量线程将被唤醒。
demo
#include <stdio.h>
#include <pthread.h>
#include <semaphore.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <time.h>
#include <errno.h>
#define NO_WAIT 0
#define WAIT_FOREVER (-1)
sem_t sem;
static inline void getTimespec(int wait_ms, struct timespec *tp)
{
time_t sec, t;
long long nsec;
sec = 0;
if (wait_ms == NO_WAIT)
{
nsec = 0;
}
else
{
nsec = wait_ms * 1000000LL;
}
if (clock_gettime(CLOCK_REALTIME, tp) == -1) //get now time
{
printf("getTimespec: clock_gettime call fail, error %d(%s)\n", errno, strerror(errno));
tp->tv_sec = time(NULL) + 1;
tp->tv_nsec = 0;
}
else
{
t = time(NULL) + 1;
if((int)(tp->tv_sec - t) > 30)
{
tp->tv_sec = t;
tp->tv_nsec = 0;
}
}
nsec += tp->tv_nsec;
if(nsec >= 1000000000)
{
sec = nsec / 1000000000;
nsec = nsec % 1000000000;
}
tp->tv_sec += sec;
tp->tv_nsec = nsec;
return;
}
int semGetvalue(sem_t * sem, int *val)
{
int rval = sem_getvalue(sem, val);
return rval;
}
int semWait(sem_t *sem, int wait_ms)
{
int rval;
struct timespec timeout;
if(wait_ms == NO_WAIT)
{
rval = sem_trywait(sem);
}
else if(wait_ms == WAIT_FOREVER)
{
rval = sem_wait(sem);
}
else
{
getTimespec(wait_ms, &timeout);
rval = sem_timedwait(sem, &timeout);
}
return rval;
}
void* produce(void* arg)
{
int sval = 0;
sleep(5);
semGetvalue(&sem, &sval); // get sem value
printf("sval is %d\n", sval);
semPost(&sem);
return NULL;
}
void * consumer(void* arg)
{
int ret;
ret = semWait(&sem, 2000);
printf(“timeout ret = %d\n”,ret);
ret = semWait(&sem, 10000);
printf("notimeout ret = %d\n",ret);
return NULL;
}
int main()
{
pthread_t p1_tid;
pthread_t p2_tid;
int ret;
ret = sem_init(&sem, 0, 0);
if(ret != 0)
return -1;
int i =1, j=2;
pthread_create(&p1_tid, NULL, produce, (void *)&i);
pthread_create(&p2_tid, NULL, consumer, (void*)&j);
pthread_join(p1_tid, NULL);
pthread_join(p2_tid, NULL);
sem_destroy(&sem);
return 0;
}