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/01 Report--
This article mainly introduces the relevant knowledge of how to use semaphores in swoole, the content is detailed and easy to understand, the operation is simple and fast, and has a certain reference value. I believe you will gain something after reading this article on how to use semaphores in swoole. Let's take a look at it.
In swoole, semaphores are mainly used to protect shared resources, so that resources have only one process at a time; when the value of semaphore is positive, it means that the tested thread can be locked and used; if the value of semaphore is 0, it means that the tested thread should enter the sleep queue and wait to be awakened.
Operating environment of this tutorial: Windows10 system, Swoole4 version, DELL G3 computer
The usage of semaphores in swoole
Semaphores are mainly used to protect shared resources, so that resources have only one process (thread) at a time.
What you have. When the value of the semaphore is positive, it is idle. The thread being tested can be locked and used. If it is 0, it means that it is occupied, and the thread tested will enter the sleep queue and wait to be awakened.
Linux provides two semaphores:
(1) Kernel semaphores, which are used by kernel control paths
(2) semaphores used by user-mode processes, which are divided into POSIX semaphores and SYSTEM semaphores.
V semaphore.
POSIX semaphores are divided into famous semaphores and unnamed semaphores.
There is a named semaphore whose value is saved in a file, so it can be used for threads or for synchronization between processes. Nameless
Semaphore, whose value is stored in memory.
Kernel semaphore
The composition of kernel semaphores
The kernel semaphore is similar to a spin lock in that it does not allow the kernel control path to continue when the lock is closed. However,
When the kernel control path tries to obtain the busy resources protected by the kernel semaphore lock, the corresponding process is suspended. The process becomes runnable again only when the resource is released.
Only functions that can sleep can get kernel semaphores; neither interrupt handlers nor delayable functions can use the
Nuclear semaphore.
Kernel semaphores are objects of type struct semaphore, which are found in the
# include # include int number; / / protected global variable sem_t sem_id;void* thread_one_fun (void* arg) {sem_wait (& sem_id); printf ("thread_one have the semaphore\ n"); number++;printf ("number =% d\ n", number); sem_post (& sem_id);} void* thread_two_fun (void* arg) {sem_wait (& sem_id) Printf ("thread_two have the semaphore\ n"); number--;printf ("number =% d\ n", number); sem_post (& sem_id);} int main (int argc,char * argv []) {number = 1 argv id1, id2;sem_init (& sem_id, 0,1); pthread_create (& id1,NULL,thread_one_fun, NULL); pthread_create (& id2,NULL,thread_two_fun, NULL); pthread_join (id1,NULL) Pthread_join (id2,NULL); printf ("main,\ n"); return 0;}
In the above routine, which thread applies for the semaphore resource first is random. If you want a particular Shun,
In order, it can be implemented with 2 semaphores. For example, the following routine is that thread 1 finishes execution before thread 2 succeeds
Continue to execute until the end.
Int number; / / protected global variables sem_t sem_id1, sem_id2;void* thread_one_fun (void* arg) {sem_wait (& sem_id1); printf ("thread_one have the semaphore\ n"); number++;printf ("number =% d\ n", number); sem_post (& sem_id2);} void* thread_two_fun (void* arg) {sem_wait (& sem_id2); printf ("thread_two have the semaphore\ n"); number- Printf ("number =% d\ n", number); sem_post (& sem_id1);} int main (int argc,char * argv []) {number = 1 id1, id2;sem_init (& sem_id1, 0,1); / / idle sem_init (& sem_id2, 0,0); / / busy pthread_create (& id1,NULL,thread_one_fun, NULL); pthread_create (& id2,NULL,thread_two_fun, NULL) Pthread_join (id1,NULL); pthread_join (id2,NULL); printf ("main,\ n"); return 0;}
(B) synchronization of anonymous semaphores between related processes
It is said that it is a related process because there are two processes in this program, one of which is a child of the other (by
Fork
Produced).
Originally, for fork, the child process only inherits the code copy of the parent process, and the mutex should be in the parent-child process.
Are independent of each other, but because when initializing mutex, it is indicated by pshared = 1
It is determined that the mutex is in the shared memory area, so the mutex becomes a change shared by the parent and child processes.
Quantity. At this point, mutex can be used to synchronize related processes.
# include # include int main (int argc, char * * argv) {int fd, iRecyclical count0memorialnlooptiles 10ptrentsemitert mutex;//open a file and map it into memoryfd = open ("log.txt", O_RDWR | Olympus creatureSeven IRWXU); write (int); ptr = mmap (NULL,sizeof (int), PROT_READ | PROT_WRITE,MAP_SHARED,fd,0); close (fd) / * create, initialize semaphore * / if (sem_init (& mutex,1,1) < 0) / / {perror ("semaphore initilization"); exit (0);} if (fork () = = 0) {/ * child process*/for (I = 0; I < nloop; ionization +) {sem_wait (& mutex); printf ("child:% d\ n", (* ptr) + +); sem_post (& mutex);} exit (0);} / * back to parent process*/for (I = 0; I < nloop) Sem_wait (& mutex); printf ("parent:% d\ n", (* ptr) + +); sem_post (& mutex);} exit (0);}
2. Famous semaphore
The characteristic of a famous semaphore is that the value of the semaphore is saved in the file.
This determines that it has a wide range of uses: it can be used not only for threads, but also for related processes, or even irrelevant.
Process.
(a) reasons why named semaphores can be shared between processes
Because the value of the named semaphore is saved in the file, for the related process, the child process inherits the parent
The file descriptor of the process, so that the file descriptor inherited by the child process points to the same file as the parent process, when the
However, the value of the famous signal stored in the file is shared.
(B) description of named semaphore correlation function
When used, named semaphores share sem_wait and sem_post functions with unnamed semaphores.
The difference is that the named semaphore uses sem_open instead of sem_init, and at the end, like closing the file.
To turn off this famous semaphore as well.
(1) Open an existing named semaphore, or create and initialize a named semaphore. A single call is over.
It becomes the creation, initialization and permission setting of semaphores.
Sem_t * sem_open (const char * name, int oflag, mode_t mode, int value)
Name is the pathname of the file
Oflag has two values: O_CREAT or O_CREAT | EXCL
Mode_t controls access to new semaphores
Value specifies the initialization value of the semaphore.
Note:
The name here cannot be written in the format / tmp/aaa.sem, because under linux, sem is created
In the / dev/shm directory. You can write name as "/ mysem" or "mysem", and all the files created
It's "/ dev/shm/sem.mysem". Never write the path. And don't write "/ tmp/mysem" or anything like that.
When oflag = O_CREAT, if the semaphore specified by name does not exist, one is created, and after
The mode and value parameters of the face must be valid. If the semaphore specified by name already exists, open the semaphore directly
Both mode and value parameters are ignored.
When oflag = O_CREAT | O_EXCL, if the semaphore specified by name already exists, the function will return directly
Go back to error.
(2) once you use semaphores, it becomes important to destroy them.
Before you do this, make sure that all references to the named semaphore have been passed through the sem_close () function
Off, and then simply call sem_unlink () in the exit or exit handler to delete the semaphore in the system
Note that if any processor or thread references this semaphore, the sem_unlink () function does not do anything.
Use it.
That is, it must be the last process that uses the semaphore to execute sem_unlick. Because every
The semaphore has a reference counter to record the current number of openings. Sem_unlink must wait for this number to be 0 before setting the
The semaphore referred to by name is removed from the file system. That is to wait for the last sem_close to happen.
(C) synchronization of named semaphores between unrelated processes
As mentioned earlier, a named semaphore is located in the shared memory area, so the resource it wants to protect must also be located in the
Share the memory area so that it can be shared by unrelated processes.
In the following example, both the service process and the client process use shmget and shmat to get a shared
Save resources. Then the named semaphore is used to protect the shared memory resource from mutual exclusion.
File1: server.c#include # define SHMSZ 27char SEM_NAME [] = "vik"; int main () {char ch;int shmid;key_t key;char * shm,*s;sem_t * mutex;//name the shared memory segmentkey = 1000 define SHMSZ 27char SEM_NAME create & initialize semaphoremutex = sem_open (SEM_NAME,O_CREAT,0644,1); if (mutex = = SEM_FAILED) {perror ("unable to create semaphore"); sem_unlink (SEM_NAME); exit (- 1) } / / create the shared memory segment with this keyshmid = shmget (key,SHMSZ,IPC_CREAT | 0666); if (shmid
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.