search
HomePHP FrameworkSwooleWhat is the usage of semaphore in swoole

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 <pthread.h>
#include <semaphore.h>
#include <sys/types.h>
#include <stdio.h>
#include <unistd.h>
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 <semaphore.h>
#include <stdio.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
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 unrelated processes.

(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 <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#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=&#39;A&#39;;ch<=&#39;Z&#39;;ch++)
{
sem_wait(mutex);
*s++ = ch;
sem_post(mutex);
}
//the below loop could be replaced by binary semaphore
while(*shm != &#39;*&#39;)
{
sleep(1);
}
sem_close(mutex);
sem_unlink(SEM_NAME);
shmctl(shmid, IPC_RMID, 0);
exit(0);
}
<u>File 2: client.c</u>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <semaphore.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#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 = &#39;*&#39;;
sem_close(mutex);
shmctl(shmid, IPC_RMID, 0);
exit(0);
}

SYSTEM V信号量

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

#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <stdio.h>
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
workerman和swoole性能谁更好?如何选择?workerman和swoole性能谁更好?如何选择?Dec 01, 2022 am 10:00 AM

workerman 对比 swoole 实际开发项目中,你会选择哪个?对于新手学哪个较好,有什么建议吗?

swoole和go选哪个?优缺点分析swoole和go选哪个?优缺点分析Mar 27, 2023 pm 03:29 PM

在现代的应用开发中,异步编程在高并发场景下变得越来越重要。Swoole和Go是两个非常流行的异步编程框架,它们都具有高效的异步能力,但是很多人在选择使用哪个框架时会陷入困境。本文将探讨如何选择Swoole和Go,以及它们的优缺点。

swoole怎么学?学会要多久?swoole怎么学?学会要多久?Mar 27, 2023 pm 03:29 PM

你学会 Swoole 需要多久呢?这个问题其实非常难回答,因为它涉及到很多因素,比如你的编程基础、学习动力、时间安排等等。不过,在这篇文章中,我将分享一些我自己学习 Swoole 的经验和建议,希望能够对你有所帮助。

探讨一下web服务器为什么不用swoole探讨一下web服务器为什么不用swooleMar 27, 2023 pm 03:29 PM

​Swoole是一个基于PHP的开源高性能网络通信框架,它提供了TCP/UDP服务器和客户端的实现,以及多种异步IO、协程等高级特性。随着Swoole日益流行,许多人开始关心Web服务器使用Swoole的问题。为什么当前的Web服务器(如Apache、Nginx、OpenLiteSpeed等)不使用Swoole呢?让我们探讨一下这个问题。

聊聊怎么在docker中搭建swoole环境聊聊怎么在docker中搭建swoole环境Jun 28, 2022 pm 09:02 PM

怎么在docker中搭建swoole环境?下面本篇文章给大家介绍一下用docker搭建swoole环境的方法,希望对大家有所帮助!

php如何让Swoole/Pool进程池实现Redis持久连接php如何让Swoole/Pool进程池实现Redis持久连接May 27, 2023 pm 05:55 PM

php让Swoole|Pool进程池实现Redis持久连接进程池,基于Swoole\Server的Manager管理进程模块实现。可管理多个工作进程,相比Process实现多进程,Process\Pool更加简单,封装层次更高,开发者无需编写过多代码即可实现进程管理功能,配合Co\Server可以创建纯协程风格的,能利用多核CPU的服务端程序。Swoole进程池实现redis数据读取如下案例,通过WorkerStart启动Redis进程池,并持久读取Redis列表数据;当WorkerStop断开

2023最新swoole视频教程推荐(从入门到高级)2023最新swoole视频教程推荐(从入门到高级)Oct 25, 2019 pm 02:09 PM

以下为大家整理了php异步通信框架Swoole的视频教程,不需要从迅雷、百度云之类的第三方平台下载,全部在线免费观看。教程由浅入深,有php基础的人就能学习,从安装到案例讲解,全面详细,帮助你更快更好的掌握Swoole框架!

怎么安装和调用Swoole(步骤分享)怎么安装和调用Swoole(步骤分享)Mar 28, 2023 am 10:17 AM

Swoole是一种基于PHP语言的网络通信框架,它能够提供异步、并发、高性能的HTTP、WebSocket以及TCP/UDP协议服务器和客户端,在开发Web服务以及网络通信应用时都有很大的用途,广泛应用于一些互联网公司。本文将介绍如何使用Swoole调用。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.