semaphore --- 信号灯 / 信号量
虽然互斥量和条件变量为线程之间的同步通信提供了一个理想的答案,但是它们不是万能的,不能满足所有的情况。比如在:在信号处理函数中要与等待异步事件的线程之间的通信(来唤醒线程),就不能用互斥量和条件变量来完成(pthread的所有函数都不能在信号处理函数中调用,都不是信号可重入的函数)。当然,我们可以在多线程中利用sigwait或者sigwaitinfo等函数来将线程中的异步时间转化成同步事件来处理。但是,使用异步的信号处理函数已经很普遍,很可能在多线程中会碰到这样的异步编码。
此时,我们可以使用POSIX semaphore,因为sem_post函数是“信号可重入函数”。我们可以在信号处理函数中使用它来唤醒一个在信号灯上等待的线程。
1. POSIX semaphore 与 System V semaphores
存在这两种信号灯/信号量的API:
- System V semaphores (semget(2), semop(2), etc.) are an older semaphore API.
- POSIX semaphores provide a simpler, and better designed interface than System V semaphores;
- on the other hand POSIX semaphores are less widely available (especially on older systems)
- than System V semaphores. (from man 7 sem_overview)
2. semaphore 是一种通用的同步机制 --- 既可以在进程中使用也可以在线程中使用
- POSIX semaphores allow processes and threads to synchronize their actions.
-
-
A semaphore is an integer whose value is never allowed to fall below zero. Two operations
- can be performed on semaphores: increment the semaphore value by one (sem_post(3)); and
- decrement the semaphore value by one (sem_wait(3)). If the value of a semaphore is
- currently zero, then a sem_wait(3) operation will block until the value becomes greater
-
than zero.(from man 7 sem_overview)
3. semaphore分成了“有名信号灯”和“无名信号灯”
这有点类似与“有名管道”和“无名管道”,有名信号灯需要自己知道一个名字(路径),它可以在任何进程之间或者任何进程之间的线程之间通信;但是无名信号灯不需要指定名字(路径),导致它只能在父子进程等有关联的进程之间或者同一个进程中的线程通信。
- POSIX semaphores come in two forms: named semaphores and unnamed semaphores.
-
-
Named semaphores
-
A named semaphore is identified by a name of the form /somename; that is, a null-terminated
- string of up to NAME_MAX-4 (i.e., 251) characters consisting of an initial slash, followed
- by one or more characters, none of which are slashes. Two processes can operate on the same
- named semaphore by passing the same name to sem_open(3).
-
-
The sem_open(3) function creates a new named semaphore or opens an existing named semaphore.
- After the semaphore has been opened, it can be operated on using sem_post(3) and sem_wait(3).
-
When a process has finished using the semaphore, it can use sem_close(3) to close the
- semaphore. When all processes have finished using the semaphore, it can be removed from the
- system using sem_unlink(3).
-
-
Unnamed semaphores (memory-based semaphores)
-
An unnamed semaphore does not have a name. Instead the semaphore is placed in a region of
- memory that is shared between multiple threads (a thread-shared semaphore) or processes (a
-
process-shared semaphore). A thread-shared semaphore is placed in an area of memory shared
- between by the threads of a process, for example, a global variable. A process-shared
- semaphore must be placed in a shared memory region (e.g., a System V shared memory segment
- created using shmget(2), or a POSIX shared memory object built created using shm_open(3)).
-
-
Before being used, an unnamed semaphore must be initialized using sem_init(3). It can then
- be operated on using sem_post(3) and sem_wait(3). When the semaphore is no longer required,
- and before the memory in which it is located is deallocated, the semaphore should be
- destroyed using sem_destroy(3).(from man 7 sem_overview)
4.Linux对semaphore的支持
- Versions
-
Prior to kernel 2.6, Linux only supported unnamed, thread-shared semaphores. On a system
- with Linux 2.6 and a glibc that provides the NPTL threading implementation, a complete
- implementation of POSIX semaphores is provided.
-
-
Persistence
-
POSIX named semaphores have kernel persistence: if not removed by sem_unlink(3),
- a semaphore will exist until the system is shut down.
-
-
Linking
-
Programs using the POSIX semaphores API must be compiled with cc -lrt to link against the
- real-time library, librt.
-
-
Accessing named semaphores via the file system
-
On Linux, named semaphores are created in a virtual file system, normally mounted under
- /dev/shm, with names of the form sem.somename.
-
(This is the reason that semaphore names are limited to NAME_MAX-4 rather than NAME_MAX
- characters.)
-
-
Since Linux 2.6.19, ACLs can be placed on files under this directory,
-
to control object permissions on a per-user and per-group basis.(from man 7 sem_overview)
5.多线程中信号灯与互斥量--条件变量的区别
1)信号灯没有“主人”的概念,也就是说:任何线程都可以释放在一个信号灯上阻塞的线程,就好像任何线程都能释放某线程已锁住的互斥量一样。
2)信号灯能独立于任何外部的状态。但是条件变量依赖于一个共享的谓词(即一个flag变量)和一个
pthread_mutex_t变量。
6.示例代码:
- #include <sys/types.h>
-
#include <unistd.h>
-
#include <pthread.h>
-
#include <semaphore.h>
-
#include <signal.h>
-
#include <time.h>
-
#include <errno.h>
-
#include <stdio.h>
-
-
sem_t semaphore;
-
-
void signal_catcher(int sig)
-
{
-
sem_post(&semaphore);
-
}
-
-
void *sem_waiter(void *arg)
-
{
-
int number = (int)arg;
-
int counter;
-
-
// Each thread waits 5 times.
-
for(counter = 1; counter <= 5; counter++){
-
while(sem_wait(&semaphore) == -1){
-
if(errno != EINTR)
-
perror("Wait on semaphore");
-
}
-
printf("%d waking (%d)...\n", number, counter);
-
}
-
return NULL;
-
}
-
-
int main(int argc, char *argv[])
-
{
-
int thread_count;
-
struct sigevent sig_event;
-
struct sigaction sig_action;
-
struct itimerspec timer_val;
-
sigset_t sig_mask;
-
timer_t timer_id;
-
pthread_t sem_waiters[5];
-
- sem_init(&semaphore, 0, 0);
-
-
// Create 5 threads to wait on a semaphore.
-
for(thread_count = 0; thread_count < 5; thread_count++){
-
pthread_create(&sem_waiters[thread_count], NULL, sem_waiter, (void *)thread_count);
-
}
-
-
/*
-
* Set up a repeating timer using signal number SIGRTMIN,
-
* set to occur every 2 seconds.
-
*/
-
sig_event.sigev_value.sival_int = 0;
-
sig_event.sigev_signo = SIGRTMIN;
-
sig_event.sigev_notify = SIGEV_SIGNAL;
-
if(timer_create(CLOCK_REALTIME, &sig_event, &timer_id) == -1)
-
perror("Create timer");
-
-
sigemptyset(&sig_mask);
-
sigaddset(&sig_mask, SIGRTMIN);
-
sig_action.sa_handler = signal_catcher;
-
sig_action.sa_mask = sig_mask;
-
sig_action.sa_flags = 0;
-
if(sigaction(SIGRTMIN, &sig_action, NULL) == -1)
-
perror("Set signal action");
-
-
timer_val.it_interval.tv_sec = 2;
-
timer_val.it_interval.tv_nsec = 0;
-
timer_val.it_value.tv_sec = 2;
-
timer_val.it_value.tv_nsec = 0;
-
if(timer_settime(timer_id, 0, &timer_val, NULL) == -1)
-
perror("Set timer");
-
-
// Wait for all threads to complete.
-
for(thread_count = 0; thread_count < 5; thread_count++){
-
pthread_join(sem_waiters[thread_count], NULL);
-
}
-
return 0;
- }
编译运行:
- digdeep@ubuntu:~/pthread/learnthread$ gcc -Wall -pthread -lrt -o semaphore semaphore_signal.c
-
digdeep@ubuntu:~/pthread/learnthread$ ./semaphore
-
0 waking (1)...
-
1 waking (1)...
-
2 waking (1)...
-
3 waking (1)...
-
4 waking (1)...
-
0 waking (2)...
-
1 waking (2)...
-
2 waking (2)...
-
3 waking (2)...
-
4 waking (2)...
-
0 waking (3)...
-
1 waking (3)...
-
2 waking (3)...
-
3 waking (3)...
-
4 waking (3)...
-
0 waking (4)...
-
1 waking (4)...
-
2 waking (4)...
-
3 waking (4)...
-
4 waking (4)...
-
0 waking (5)...
-
1 waking (5)...
-
2 waking (5)...
-
3 waking (5)...
-
4 waking (5)...
-
digdeep@ubuntu:~/pthread/learnthread$
阅读(4414) | 评论(0) | 转发(0) |