1. 信号量:
简述:用于进程传递信号的一个整数值。它在linux C++中表示为sem_t包含在
操作:
函数sem_init原型如下:
/* Initialize semaphore object SEM to VALUE. If PSHARED then share it
with other processes. */
extern int sem_init (sem_t *__sem, int __pshared, unsigned int __value)
__THROW;
参数介绍:
__sem为需要初始的sem_t的指针
__pshared为共享属性。不为0则在进程间共享,否则只在本进程间共享。
__value给出了信号量的初始值
函数sem_post原型如下:
/* Post SEM. */
extern int sem_post (sem_t *__sem) __THROWNL;
作用就是将传入的信号量的值加1。当有线程在该信号量阻塞的话,线程就可以从队列中被放出来执行。
函数sem_wait原型如下:
/* Wait for SEM being posted.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int sem_wait (sem_t *__sem);
作用就是将传入的信号量的值减1。当信号量的值为负数时,该线程被阻塞,并且放到队列里面,等到锁释放。
函数sem_destory原型如下:
/* Free resources associated with semaphore object SEM. */
extern int sem_destroy (sem_t *__sem) __THROW;
作用就是释放信号量。
2. 条件信号量
简述:条件变量其实和信号量很像,只是在条件为真的时候才可以获得锁。它在linux c++中表示为pthread_cond_t,包含在
操作:
函数pthread_cond_init原型如下:
/* Initialize condition variable COND using attributes ATTR, or use
the default values if later is NULL. */
extern int pthread_cond_init (pthread_cond_t *__restrict __cond,
const pthread_condattr_t *__restrict __cond_attr)
__THROW __nonnull ((1));
参数介绍:
__cond需要初始的条件信号量指针。
__cond_attr条件信号量的属性变量。
和互斥锁一样,条件信号量可以设置为同一个进程中共享,还是不同进程之间共享,默认为PTHREAD_ PROCESS_PRIVATE。即只有同一个进程中共享。
函数pthread_wait函数原型如下:
/* Wait for condition variable COND to be signaled or broadcast.
MUTEX is assumed to be locked before.
This function is a cancellation point and therefore not marked with
__THROW. */
extern int pthread_cond_wait (pthread_cond_t *__restrict __cond,
pthread_mutex_t *__restrict __mutex)
__nonnull ((1, 2));
参数介绍:
__cond为某个条件信号量的指针。
__mutex为某个之前加上的锁。
该函数的作用在于,如果条件信号量不满足条件,则阻塞,注意,在这个函数进入的时候会先解掉传入的锁,然后等待条件变量的变化,函数返回的时候才将锁释放。其实我发现这东西和信号量没什么两样,可能我还不了解它的精髓。
函数pthread_cond_signal函数原型如下:
/* Wake up one thread waiting for condition variable COND. */
extern int pthread_cond_signal (pthread_cond_t *__cond)
__THROWNL __nonnull ((1));
这个函数的作用就是将cond的值加1,和信号量的作用是一样的。