- inux_信号量(sem_t)&sem_wait&sem_post
- references
- sem_t的定义
- sem_post(3) - Linux man page
- Name
- Synopsis
- Description
- sem_wait(3) - Linux man page
- Name
- Synopsis
- Description
- Return Value
- sem_overview(7) - Linux man page
- Name
- Description
- Versions
- Persistence
- 例程
-
sem_wait(3): lock semaphore - Linux man page (die.net)
-
sem_post(3): unlock semaphore - Linux man page (die.net)
-
Semaphores and Mutexes (niu.edu)
What is a semaphore in LINUX?
A semaphore is fundamentally an integer whose value is never allowed to fall below 0. There are two operations on a semaphore: wait and post. The post operation increment the semaphore by 1, and the wait operations does the following: If the semaphore has a value > 0, the semaphore is decremented by 1. If the semaphore has value 0, the caller will be blocked (busy-waiting or more likely on a queue) until the semaphore has a value larger than 0, and then it is decremented by 1.
We declare a semaphore as:
sem_t sem;
where sem_t is a typedef defined in a header file as (apparently) a kind of unsigned char.
An example of this might be that we have a set of N interchangeable resources. We start with semaphore S = N. We use a resource, so there are now N-1 available (wait), and we return it when we are done (post). If the semaphore has value 0, there are no resources available, and we have to wait (until someone does a post).
Semaphores are thus used to coordinate concurrent processes.
This is what some people call a “counted semaphore”. There is a similar notion called a “binary semaphore” which is limited to the values 0 and 1.
A semaphore may be named or unnamed. These notes assume we are using named semaphores.
sem_t的定义typedef union
{
char __size[__SIZEOF_SEM_T];
long int __align;
} sem_t;
sem_post(3) - Linux man page
Name
sem_post - unlock a semaphore
Synopsis#includeint sem_post(sem_t *sem);
Link with -pthread.
Descriptionsem_post() increments (unlocks) the semaphore pointed to by sem. If the semaphore’s value consequently becomes greater than zero, then another process or thread blocked in a sem_wait(3) call will be woken up and proceed to lock the semaphore.
sem_wait(3) - Linux man page Namesem_wait, sem_timedwait, sem_trywait - lock a semaphore
Synopsis#includeint sem_wait(sem_t *sem); int sem_trywait(sem_t *sem); int sem_timedwait(sem_t *sem, const struct timespec *abs_timeout);
Link with -pthread.
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
- sem_timedwait(): _POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600
sem_wait() decrements (locks) the semaphore pointed to by sem. If the semaphore’s value is greater than zero, then the decrement proceeds, and the function returns, immediately. If the semaphore currently has the value zero, then the call blocks until either it becomes possible to perform the decrement (i.e., the semaphore value rises above zero), or a signal handler interrupts the call.
sem_trywait() is the same as sem_wait(), except that if the decrement cannot be immediately performed, then call returns an error (errno set to EAGAIN) instead of blocking.
sem_timedwait() is the same as sem_wait(), except that abs_timeout specifies a limit on the amount of time that the call should block if the decrement cannot be immediately performed. The abs_timeout argument points to a structure that specifies an absolute timeout in seconds and nanoseconds since the Epoch, 1970-01-01 00:00:00 +0000 (UTC). This structure is defined as follows:
struct timespec {
time_t tv_sec;
long tv_nsec;
};
If the timeout has already expired by the time of the call, and the semaphore could not be locked immediately, then sem_timedwait() fails with a timeout error (errno set to ETIMEDOUT).
If the operation can be performed immediately, then sem_timedwait() never fails with a timeout error, regardless of the value of abs_timeout. Furthermore, the validity of abs_timeout is not checked in this case.
Return ValueAll of these functions return 0 on success; on error, the value of the semaphore is left unchanged, -1 is returned, and errno is set to indicate the error.
sem_overview(7) - Linux man page Namesem_overview - overview of POSIX semaphores
DescriptionPOSIX 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.
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 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).
The remainder of this section describes some specific details of the Linux implementation of POSIX semaphores.
VersionsPrior 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.
PersistencePOSIX named semaphores have kernel persistence: if not removed by sem_unlink(3), a semaphore will exist until the system is shut down.
例程#include#include #include #include #include int main(int argc, char const *argv[]) { sem_t s; sem_init(&s, 0, 3); // 注意fork的新进程要共享s pid_t pid = fork(); if (pid == 0) { sleep(1); sem_post(&s); sem_post(&s); sem_post(&s); printf("by child:@s.__align:%ldn", s.__align); exit(1); } else { printf("查看初始值:@s.__align:%ldn", s.__align); printf("开始调用sem_wait若干次...n"); printf("@1"); sem_wait(&s); printf("@s.__align:%ldn", s.__align); printf("@2"); sem_wait(&s); printf("@s.__align:%ldn", s.__align); printf("@3"); sem_wait(&s); printf("@s.__align:%ldn", s.__align); printf("waiting...n"); printf("开始被阻塞,直到被另一个进程的sem_post唤醒!n"); sem_wait(&s); printf("@s.__align:%ldn", s.__align); wait(NULL); } return 0; }
尚未理解结果_有待探究
# cxxu @ cxxuAli in ~/cppCodes/barber on git:master x [21:34:48] $ sem_test 查看初始值:@s.__align:3 开始调用sem_wait若干次... @1@s.__align:2 @2@s.__align:1 @3@s.__align:0 waiting... 开始被阻塞,直到被另一个进程的sem_post唤醒! by child:@s.__align:6



