PHP下通过系统信号量加锁方式获取递增序列ID_PHP
在网上搜了搜,有两个办法但都不太好:一个是简单的以进程ID+时间戳,或进程ID+随机数来产生近似的唯一ID,虽简单但对于追求“完美”的我不愿这样凑合,再说Apache2以后进程会维持相当长得时间,生成的ID发生碰撞的几率还是比较大的;第二个思路是通过Mysql的自增字段,这个就更不能考虑了,效率低不说,我的设计里压根就没数据库。
递增ID的获取是个过程:
1. 从全局某个存储中读取ID
2. 给ID加1
3. 将ID重新存入全局存储
在多进程或线程的程序中需要将上述3步作为单步的原子操作,才能保证ID的唯一。
Java中很好解决,这是因为Java程序大多以多线程方式运行,每个线程都能共享Java进程中的变量,并能方便的加线程锁控制线程的运转同步。在PHP中ID全局存储没问题,可以放在session中,大不了放在文件中,但进程间同步就是问题了。
实际上进程调度、管理是操作系统内核必须实现的功能,今天介绍的信号量(也称为信号灯)就是在Unix/Linux上解决进程同步的一项技术。
信号灯原是用在铁路上的管理机制,我们今天看到的铁路大多是双线并行,但有的路段受山势、地形影响只有单条铁轨,必须保证同一时间只能有一列火车运行通过这些路段。早先铁路上就是用信号灯来管理的:没有火车经过时,信号等处于闲置状态,一旦有火车进入此路段,信号灯即变为在用状态,其他的火车经过时就需要等待,等待先前的火车驶出路段信号等变为闲置后,才能进入此路段,一旦又有火车进入,信号灯又变为繁忙......,以此来保障铁路运行的安全畅通。
Unix系统就像铁路管理局控制信号灯一样管理控制信号量的状态,因此也可以这样说信号量是由内核管理的,信号量不仅能控制进程间的同步,同样可以控制线程间的同步。
信号量属于系统进程间通讯技术(IPC),今天我们只从PHP角度介绍信号量的使用,有关IPC的技术细节可参考Stevens的权威著作《UNIX网络编程第二卷 进程间通信》。
先看最终的代码:
复制代码 代码如下:
// ---------------------------------------------------
// 递增序列号ID(1~1000000000)
//
// ID存储在共享内存中(shared memory),通过信号灯(semaphore)同步
// ---------------------------------------------------
$IPC_KEY = 0x1234; //System V IPC KEY
$SEQ_KEY = "SEQ"; //共享内存中存储序列号ID的KEY
//创建或获得一个现有的,以"1234"为KEY的信号量
$sem_id = sem_get($IPC_KEY);
//创建或关联一个现有的,以"1234"为KEY的共享内存
$shm_id = shm_attach($IPC_KEY, 64);
//占有信号量,相当于上锁,同一时间内只有一个流程运行此段代码
sem_acquire($sem_id);
//从共享内存中获得序列号ID
$id = @shm_get_var($shm_id, $SEQ_KEY);
if ($id == NULL || $id >= 1000000000)
{
$id = 1;
}
else
{
$id++;
}
//将"++"后的ID写入共享内存
shm_put_var($shm_id, $SEQ_KEY, $id);
//释放信号量,相当于解锁
sem_release($sem_id);
//关闭共享内存关联
shm_detach($shm_id);
echo "序列号ID:{$id}";
?>
009行,定义了一个16进制的整形KEY,在PHP中只支持System V的IPC机制,需要通过一个KEY关联到指定的资源(消息队列、信号量、共享内存)。
010 行,定义了一个在共享内存中存储递增ID的KEY,这是PHP对System V共享内存的闲置:需要通过类似hashtable的KEY-VALUE方式存储变量。在上面的代码中使用共享内存做ID的存储容器,也可以换为 Session、文件等其他机制,本文重点是信号量,有关共享内存的知识以后在讲(别忘了前面推荐的那本书)。
013行,获得系统中的以1234为KEY的信号量,如果系统中没有就创建一个。
015行,同13行相似,获得系统中的以1234为KEY的共享内存,如果系统中没有就创建一个,第二个参数64表示创建64bytes大小的共享内存。
018~034 行,同步代码区,当一个进程或线程执行sem_acquire函数占有了信号量,到它调用sem_release函数释放信号量的过程内,其他进程或线程执行到sem_acquire会阻塞。021行从共享内存中获得ID,函数shm_get_var前缀"@"是为了屏蔽出错信息(第一次执行时,共享内存中并没有以"SEQ"为KEY的数据,会在页面上打印警告信息)。
其他语句非常简单,不需多讲。
程序编好后,访问这个PHP页面,会递增的输出数字。
我们可以通过系统命令ipcs查看在程序创建的信号量和共享内存:
$ ipcs
------ Shared Memory Segments --------
key shmid owner perms bytes nattch status
0x00001234 1212443 www-data 666 64 0
------ Semaphore Arrays --------
key semid owner perms nsems
0x00001234 163841 www-data 666 3
------ Message Queues --------
key msqid owner perms used-bytes messages
前两段分别是共享内存和信号量,0x00001234既是我们创建的KEY。
也可以通过命令ipcrm删除:
$ ipcrm -M 0x00001234 #删除共享内存
$ ipcrm -S 0x00001234 #删除信号量
---------------------------------------------
PHP手册中关于IPC的资料非常少,这点也不难想象,Stevens已经在十几年前讲得透透的东东,在PHP中只是包装了一下,还有多少必要去深入说明呢?
文本只是借着ID说了说信号量的使用,如果您有更简单的生成自增ID的办法,还望赐教。
可能有朋友还想了解信号量的执行效率,我这里用一句过时的流行语总结: 相当的快。

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



If you find event ID 55, 50, 140 or 98 in the Event Viewer of Windows 11/10, or encounter an error that the disk file system structure is damaged and cannot be used, please follow the guide below to resolve the issue. What does Event 55, File system structure on disk corrupted and unusable mean? At session 55, the file system structure on the Ntfs disk is corrupted and unusable. Please run the chkMSK utility on the volume. When NTFS is unable to write data to the transaction log, an error with event ID 55 is triggered, which will cause NTFS to fail to complete the operation unable to write the transaction data. This error usually occurs when the file system is corrupted, possibly due to the presence of bad sectors on the disk or the file system's inadequacy of the disk subsystem.

When logging into iTunesStore using AppleID, this error saying "This AppleID has not been used in iTunesStore" may be thrown on the screen. There are no error messages to worry about, you can fix them by following these solution sets. Fix 1 – Change Shipping Address The main reason why this prompt appears in iTunes Store is that you don’t have the correct address in your AppleID profile. Step 1 – First, open iPhone Settings on your iPhone. Step 2 – AppleID should be on top of all other settings. So, open it. Step 3 – Once there, open the “Payment & Shipping” option. Step 4 – Verify your access using Face ID. step

In Alibaba software, once you successfully register an account, the system will assign you a unique ID, which will serve as your identity on the platform. But for many users, they want to query their ID, but don't know how to do it. Then the editor of this website will bring you detailed introduction to the strategy steps below. I hope it can help you! Where can I find the answer to Alibaba ID: [Alibaba]-[My]. 1. First open the Alibaba software. After entering the homepage, we need to click [My] in the lower right corner; 2. Then after coming to the My page, we can see [id] at the top of the page; Alibaba Is the ID the same as Taobao? Alibaba ID and Taobao ID are different, but the two
![Event ID 4660: Object deleted [Fix]](https://img.php.cn/upload/article/000/887/227/168834320512143.png?x-oss-process=image/resize,m_fill,h_207,w_330)
Some of our readers encountered event ID4660. They're often not sure what to do, so we explain it in this guide. Event ID 4660 is usually logged when an object is deleted, so we will also explore some practical ways to fix it on your computer. What is event ID4660? Event ID 4660 is related to objects in Active Directory and will be triggered by any of the following factors: Object Deletion – A security event with Event ID 4660 is logged whenever an object is deleted from Active Directory. Manual changes – Event ID 4660 may be generated when a user or administrator manually changes the permissions of an object. This can happen when changing permission settings, modifying access levels, or adding or removing people or groups

Where can I check the Tencent Video ID? There is an exclusive ID in the Tencent Video APP, but most users do not know how to check the Tencent Video ID. Next is the graphic tutorial on how to check the Tencent Video ID brought by the editor for users who are interested. Users come and take a look! Tencent Video Usage Tutorial Where to check Tencent Video ID 1. First open the Tencent Video APP and enter the special area through [Personal Center] in the lower right corner of the main page; 2. Then enter the Personal Center page and select the [Settings] function; 3. Then go to Settings page, click [Exit Account] at the bottom; 4. Finally, you can view the exclusive ID number on the page shown below.

Vue cannot obtain the id attribute because getElementById is used in the "created()" hook function, and Vue has not completed mounting; the solution is to "created() {let serachBox = document.getElementById('searchBox') ;...}" code can be migrated to the "mounted()" hook function.

In the Linux operating system, each running program is a process, and each process has a unique process identifier (PID). Similarly, each process will have a parent process, which is the process that created it. The identifier of the parent process is called the parent process ID (PPID). In this article, we will explore how to find the ID of a parent process in a Linux system and introduce some effective commands and tools to help you get detailed information about the relationship between processes. Basic commands to find parent process ID First, I will briefly introduce you to a few basic commands that can be used to view all processes running in the system and their parent process ID. Use the ps command to view process information. The ps command is a powerful tool that is used to report

Commonly used distributed ID solutions In distributed systems, it is very important to generate globally unique IDs, because in distributed systems, multiple nodes generating IDs at the same time may cause ID conflicts. The following introduces several commonly used distributed ID solutions. UUIDUUID (Universally Unique Identifier) is an identifier composed of 128 digits, which can guarantee global uniqueness because its generation algorithm is based on factors such as timestamp, node ID and so on. UUID can be generated using Java's own UUID class, as shown below: javaCopycodeimportjava.util.UUID;publicclassUuidGenerator{publicstat
