Home>Article>PHP Framework> What is the usage of semaphore in swoole

What is the usage of semaphore in swoole

WBOY
WBOY Original
2022-03-14 15:29:31 1971browse

In swoole, the semaphore is mainly used to protect shared resources, so that the resource has only one process at a time; when the value of the semaphore is positive, it means that the thread under test can be locked for use. The semaphore If the value is 0, it means that the tested thread will enter the sleep queue and wait to be awakened.

What is the usage of semaphore in swoole

The operating environment of this tutorial: Windows10 system, Swoole4 version, DELL G3 computer

What is the usage of semaphore in swoole

The use of semaphores is mainly used to protect shared resources so that the resources are owned by only one process (thread) at a time

. When the value of the semaphore is positive, it means it is idle. The thread being tested can lock while using it. If it is 0, it means that it is occupied, and the test thread will enter the sleep queue and wait to be awakened.

Linux provides two kinds of semaphores:

(1) Kernel semaphore, used by the kernel control path

(2) Used by user mode processes semaphore, which is divided into POSIX semaphore and SYSTEM

V semaphore.

POSIX semaphores are divided into named semaphores and unnamed semaphores.

Named semaphore, its value is stored in a file, so it can be used for threads and for synchronization between processes. An unnamed

semaphore whose value is stored in memory.

Kernel semaphore

The composition of the kernel semaphore

The kernel semaphore is similar to a spin lock, because when the lock is closed, it does not Allow the kernel control path to proceed. However,

When the kernel control path attempts to acquire the busy resource protected by the kernel semaphore lock, the corresponding process is suspended. Only when the resource is released does the process become runnable again.

Only functions that can sleep can obtain kernel semaphores; neither interrupt handlers nor deferrable functions can use internal

core semaphores.

The kernel semaphore is an object of struct semaphore type. In the routine above

#include  #include  #include  #include  #include  int number; // 被保护的全局变量 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; pthread_t 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; }

, it is random which thread applies for the semaphore resource first. If you want a specific sequence, you can use 2 semaphores to achieve it. For example, in the following routine, thread 1 finishes executing first, and then thread 2 continues

until it ends.

int number; // 被保护的全局变量 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; pthread_t id1, id2; sem_init(&sem_id1, 0, 1); // 空闲的 sem_init(&sem_id2, 0, 0); // 忙的 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 unnamed semaphores between related processes

It is said to be related processes because there are two processes in this program, one of which is a child process of the other (by

fork

produced).

Originally for fork, the child process only inherits the code copy of the parent process. Mutex should be two independent variables in the parent and child processes

. However, when mutex is initialized , pshared = 1 indicates that mutex is in the shared memory area, so at this time mutex becomes a variable shared by the parent and child processes. At this point, mutex can be used to synchronize related processes.

#include  #include  #include  #include  #include  #include  #include  #include  #include  int main(int argc, char **argv) { int fd, i,count=0,nloop=10,zero=0,*ptr; sem_t mutex; //open a file and map it into memory fd = open("log.txt",O_RDWR|O_CREAT,S_IRWXU); write(fd,&zero,sizeof(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; i++) { sem_wait(&mutex); printf("child: %d\n", (*ptr)++); sem_post(&mutex); } exit(0); } /* back to parent process */ for (i = 0; i < nloop; i++) { sem_wait(&mutex); printf("parent: %d\n", (*ptr)++); sem_post(&mutex); } exit(0); }

2. Named semaphore

The characteristic of a named semaphore is to save the value of the semaphore in a file.

This determines that it has a very wide range of uses: it can be used for threads, related processes, and even unrelatedprocesses.

(a) The reason why a named semaphore can be shared between processes

Because the value of a named semaphore is stored in a file, the child process inherits it for the related process. The file descriptor of the parent process, then the file descriptor inherited by the child process points to the same file as the parent process. Of course, the named semaphore value saved in the file is Shared.

(b) Description of functions related to named semaphores

When the named semaphore is used, it shares the sem_wait and sem_post functions with the unnamed semaphore.

The difference is that the named semaphore uses sem_open instead of sem_init. In addition, at the end, the named semaphore must be closed like a file

.

(1) Open an existing named semaphore, or create and initialize a named semaphore. A single call completes the creation, initialization and permission setting of the semaphore.

sem_t *sem_open(const char *name, int oflag, mode_t mode, int value);

name is the path name of the file;

Oflag has O_CREAT or O_CREAT| EXCL has two values;

mode_t controls the access rights of the new semaphore;

Value specifies the initialization value of the semaphore.

Note:

The name here cannot be written in the format of /tmp/aaa.sem, because under Linux, sem is created

in the /dev/shm directory Down. You can write the name as "/mysem" or "mysem", and the created files will be "/dev/shm/sem.mysem". Do not write the path. Also never write "/tmp/mysem" or something like that.

When oflag = O_CREAT, if the semaphore specified by name does not exist, one will be created, and the following

mode and value parameters must be valid. If the semaphore specified by name already exists, open the semaphore directly,

and ignore the mode and value parameters.

When oflag = O_CREAT|O_EXCL, if the semaphore specified by name already exists, the function will directly return

error.

(2) Once you use semaphores, it is important to destroy them.

在做这个之前,要确定所有对这个有名信号量的引用都已经通过sem_close()函数

关闭了,然后只需在退出或是退出处理函数中调用sem_unlink()去删除系统中的信号量,

注意如果有任何的处理器或是线程引用这个信号量,sem_unlink()函数不会起到任何的作

用。

也就是说,必须是最后一个使用该信号量的进程来执行sem_unlick才有效。因为每个

信号灯有一个引用计数器记录当前的打开次数,sem_unlink必须等待这个数为0时才能把

name所指的信号灯从文件系统中删除。也就是要等待最后一个sem_close发生。

(c)有名信号量在无相关进程间的同步

前面已经说过,有名信号量是位于共享内存区的,那么它要保护的资源也必须是位于

共享内存区,只有这样才能被无相关的进程所共享。

在下面这个例子中,服务进程和客户进程都使用shmget和shmat来获取得一块共享内

存资源。然后利用有名信号量来对这块共享内存资源进行互斥保护。

File1: server.c #include  #include  #include  #include  #include  #include  #include  #include  #define SHMSZ 27 char SEM_NAME[]= "vik"; int main() { char ch; int shmid; key_t key; char *shm,*s; sem_t *mutex; //name the shared memory segment key = 1000; //create & initialize semaphore mutex = 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 key shmid = shmget(key,SHMSZ,IPC_CREAT|0666); if(shmid<0) { perror("failure in shmget"); exit(-1); } //attach this segment to virtual memory shm = shmat(shmid,NULL,0); //start writing into memory s = shm; for(ch='A';ch<='Z';ch++) { sem_wait(mutex); *s++ = ch; sem_post(mutex); } //the below loop could be replaced by binary semaphore while(*shm != '*') { sleep(1); } sem_close(mutex); sem_unlink(SEM_NAME); shmctl(shmid, IPC_RMID, 0); exit(0); } File 2: client.c #include  #include  #include  #include  #include  #include  #include  #include  #define SHMSZ 27 char SEM_NAME[]= "vik"; int main() { char ch; int shmid; key_t key; char *shm,*s; sem_t *mutex; //name the shared memory segment key = 1000; //create & initialize existing semaphore mutex = sem_open(SEM_NAME,0,0644,0); if(mutex == SEM_FAILED) { perror("reader:unable to execute semaphore"); sem_close(mutex); exit(-1); } //create the shared memory segment with this key shmid = shmget(key,SHMSZ,0666); if(shmid<0) { perror("reader:failure in shmget"); exit(-1); } //attach this segment to virtual memory shm = shmat(shmid,NULL,0); //start reading s = shm; for(s=shm;*s!=NULL;s++) { sem_wait(mutex); putchar(*s); sem_post(mutex); } //once done signal exiting of reader:This can be replaced by another semaphore *shm = '*'; sem_close(mutex); shmctl(shmid, IPC_RMID, 0); exit(0); }

SYSTEM V信号量

这是信号量值的集合,而不是单个信号量。相关的信号量操作函数由

#include  #include  #include  #include  static int nsems; static int semflg; static int semid; int errno=0; union semun { int val; struct semid_ds *buf; unsigned short *array; }arg; int main() { struct sembuf sops[2]; //要用到两个信号量,所以要定义两个操作数组 int rslt; unsigned short argarray[80]; arg.array = argarray; semid = semget(IPC_PRIVATE, 2, 0666); if(semid < 0 ) { printf("semget failed. errno: %d\n", errno); exit(0); } //获取0th信号量的原始值 rslt = semctl(semid, 0, GETVAL); printf("val = %d\n",rslt); //初始化0th信号量,然后再读取,检查初始化有没有成功 arg.val = 1; // 同一时间只允许一个占有者 semctl(semid, 0, SETVAL, arg); rslt = semctl(semid, 0, GETVAL); printf("val = %d\n",rslt); sops[0].sem_num = 0; sops[0].sem_op = -1; sops[0].sem_flg = 0; sops[1].sem_num = 1; sops[1].sem_op = 1; sops[1].sem_flg = 0; rslt=semop(semid, sops, 1); //申请0th信号量,尝试锁定 if (rslt < 0 ) { printf("semop failed. errno: %d\n", errno); exit(0); } //可以在这里对资源进行锁定 sops[0].sem_op = 1; semop(semid, sops, 1); //释放0th信号量 rslt = semctl(semid, 0, GETVAL); printf("val = %d\n",rslt); rslt=semctl(semid, 0, GETALL, arg); if (rslt < 0) { printf("semctl failed. errno: %d\n", errno); exit(0); } printf("val1:%d val2: %d\n",(unsigned int)argarray[0],(unsigned int)argarray[1]); if(semctl(semid, 1, IPC_RMID) == -1) { Perror(“semctl failure while clearing reason”); } return(0); }

推荐学习:swoole教程

The above is the detailed content of What is the usage of semaphore in swoole. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn