In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the differences between POSIX famous semaphores and unnamed semaphores". Interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Next, let the editor take you to learn "what is the difference between POSIX famous semaphores and anonymous semaphores?"
Difference
The difference between named semaphores and unnamed semaphores lies in the form of creation and destruction, but everything else works the same.
Unnamed semaphores can only exist in memory, which requires that processes that use semaphores must be able to access this piece of memory where semaphores are located, so anonymous semaphores can only be applied between threads within the same process (the memory of shared processes). Or threads in different processes that have mapped the same memory content to their address space (that is, the memory in which the semaphore is located is shared by the processes that communicate). This means that unnamed semaphores can only be accessed through shared memory.
Instead, named semaphores can be accessed by name, so they can be used by threads in any process that knows their names.
Unnamed semaphores are simpler when POSIX semaphores are used in a single process. When POSIX semaphores are used between multiple processes, named semaphores are simpler.
contact
Whether it is a named semaphore or an unnamed semaphore, you can use the following function to operate the signal value.
Wait
Weit is a semaphore value minus one operation. There are a total of three functions. The function prototype is as follows:
# include int 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. This sentence means that when gcc compiles, add-pthread. Return value: 0 if successful;-1 copy code if error occurs
The first function is that if sem is less than 0, the thread blocks the semaphore sem until sem is greater than 0; otherwise, the semaphore value is minus 1.
The second function works the same as the first, except that it does not block the thread and directly returns an error (the error is set to EAGAIN) if sem is less than 0.
The third function works the same as the first one. The second parameter represents the blocking time. If sem is less than 0, it will block, and the parameter specifies the blocking time. Abs_timeout points to a structure consisting of seconds and nanoseconds from 1970-01-01 00:00:00 + 0000 (www.taobao-wd.com). The structure is defined as follows:
Struct timespec {time_t tv_sec; / * Seconds * / long tv_nsec; / * Nanoseconds [0.. 999999999] * /}; copy the code
If the specified blocking time is up, but sem is still less than 0, an error is returned (the error is set to ETIMEDOUT).
Post
Post is the operation of adding one to the value of the signal. The function prototype is as follows:
# include int sem_post (sem_t * sem); Link with-pthread. Return value: if successful, return 0; if error, return-1 copy code to apply instance named semaphore
Create
You can call the sem_open function when creating a named semaphore. The function is described as follows:
# include sem_t * sem_open (const char * name, int oflag); sem_t * sem_open (const char * name, int oflag, mode_t mode, unsigned int value); Link with-pthread. Return value: if successful, return the pointer to the semaphore; if there is an error, return SEM_FALLED copy code
The first function is called when an existing named semaphore is used, with the flag parameter set to 0.
If the second function is to be called, the flag parameter should be set to O_CREAT, and if a named semaphore does not exist, a new one will be created, if it does, it will be used and will not be initialized.
When we use the O_CREAT flag, we need to provide two additional parameters:
The mode parameter specifies who can access the semaphore, that is, the permission group. The value of mode is the same as the permission bit to open the file. For example, 0666 indicates that all users can read and write. Because only read and write access matters, implementations often turn on semaphores for read and write.
Value specifies the initial value of the semaphore in the range of 0~SEM_VALUE_MAX.
If the semaphore exists, calling the second function ignores the last two parameters (that is, mode and value).
Release
When the semaphore operation is completed, the sem_close function can be called to release any semaphore resources. The function is described as follows:
# include int sem_close (sem_t * sem); Link with-pthread. Return value: 0 if successful;-1 copy code if error occurs
If the process exits without calling the function, the kernel automatically closes any open semaphores. Neither the call to this function nor the automatic shutdown of the kernel changes the value of the signal before it is released.
Destroy
You can use the sem_unlink function to destroy a named semaphore. The function is described as follows:
# include int sem_unlink (const char * name); Link with-pthread. Return value: 0 if successful;-1 copy code if error occurs
The sem_unlink function deletes the name of the semaphore. If there is no open semaphore reference, the semaphore is destroyed, otherwise, destruction is postponed until the last open reference is closed.
Examples
For example, in pipeline communication, if the parent process uses fork () to create two child processes 1 and 2, the child process 1, 2, writes a paragraph of text to the pipe sequentially, and finally the parent process reads the contents written by the child process from the pipeline. To ensure the order in which the processes are executed, it can be solved with a named semaphore.
# include#include#include#include#include#include#include#include#include # includeint main () {int pid1,pid2; sem_t * resource1; sem_t * resource2; int Cpid1,Cpid2=-1; int fd [2]; / 0 is the readout segment, 1 is the write end char outpipe1, inpipe, outpipe2; pipe (fd); / / establish an unnamed pipeline pid1 = fork () If (pid10) {resource2=sem_open ("name_sem2", Olympiad creation); sem_wait (resource2); waitpid (pid1,NULL,0); waitpid (pid2,NULL,0); close (fd [1]); / / turn off read (fd [0], inpipe,200) Printf ("% s\ n", inpipe); sem_close (resource2); exit (0);} sem_unlink ("name_sem1"); sem_unlink ("name_sem2");} return 0;} copy code unnamed semaphore
Create
Unnamed semaphores can be created through the sem_init function, which is described as follows:
# include int sem_init (sem_t * sem, int pshared, unsigned int value); Link with-pthread. Return value: 0 if successful;-1 copy code if error occurs
The pshared parameter indicates whether the semaphore is shared by multiple threads of a process or by multiple processes.
If the value of www.sinorichmake.com is 0, the semaphore will be shared by multiple threads in the single process and should be at an address that is visible to all threads (for example, global variables or variables are dynamically allocated on the heap).
If the pshared is non-zero, the semaphore will be shared between processes, and the semaphore should be in the shared memory area.
Destroy
If the unnamed semaphore is finished, you can call the sem_destory function to destroy the semaphore. The function is described as follows:
# include int sem_destroy (sem_t * sem); Link with-pthread. Return value: 0 if successful;-1 copy code if error occurs
Note:
Destroying semaphores that are currently blocked by other processes or threads results in undefined behavior.
Using a destroyed semaphore produces undefined results unless the semaphore is reinitialized using sem_init.
An unnamed semaphore should be destroyed with sem_destroy before its memory is freed. Failure to do so may result in resource leaks in some implementations.
Examples
Use anonymous semaphores to implement examples in famous semaphores:
# include#include#include#include#include#include#include#include#include # include# includeint main () {int pid1,pid2; int Cpid1,Cpid2=-1; int fd [2]; / 0 is the readout segment, 1 is the write side char outpipe1, inpipe, outpipe2; void * shm = NULL; sem_t * shared; int shmid = shmget ((key_t) (1234), sizeof (sem_t *), 0666 | IPC_CREAT) / / create a shared memory and return an identifier if (shmid = =-1) {perror ("shmat:"); exit (0);} shm = shmat (shmid, 0,0); / / return a pointer to the first byte of shared memory shared = (sem_t *) shm; sem_init (shared, 1,0); / / initialize the shared memory signal value to 0 pipe (fd) / / establish an anonymous pipeline pid1 = fork (); if (pid10) {waitpid (pid2,NULL,0); / / synchronize to ensure that the child process writes the parent process before reading the close (fd [1]); / / turns off the write side read (fd [0], inpipe,200); printf ("% s\ n", inpipe) Exit (0);}} return 0;} at this point, I believe you have a deeper understanding of "what is the difference between POSIX famous semaphores and unnamed semaphores". You might as well do it in practice! Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.