Home Backend Development PHP Tutorial PHP并发操作上的加锁

PHP并发操作上的加锁

Jun 13, 2016 pm 01:04 PM
eaccelerator gt lock name this

PHP并发操作下的加锁

php如何解决多线程读写同一文件

大家都知道,PHP是没有多线程概念的,尽管如此我们仍然可以用“不完美”的方法来模拟多线程。简单的说,就是队列处理。通过对文件进行加锁和解锁,来实 现。当一个文件被一个用户操作时,该文件是被锁定的,其他用户只能等待,确实不够完美,但是也可以满足一些要求不高的应用。

有这么一个需求:生成文件的时候,由于多用户都有权限进行生成,防止并发下,导致生成的结果出现错误,需要对生成的过程进行加锁,只容许一个用户在 一个时间内进行操作,这个时候就需要用到锁了,将这个操作过程锁起来。在用了cache的时候,cache失效可能导致瞬间的多数并发请求穿透到数据库此 时也可以得需要用锁在同一并发的过程中将这个操作锁定。

针对以上的2种情况,现在的解决方法是对处理过程进行锁机制,通过PHP实现如下:

用到了Eaccelerator的内存锁和文件锁,原理:判断系统中是否安了EAccelerator如果有则使用内存锁,如果不存在,则进行文件锁。根据带入的key的不同可以实现多个锁直接的并行处理,类似Innodb的行级锁。

具体类如下:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

<?php

/**

 * CacheLock 进程锁,主要用来进行cache失效时的单进程cache获取,防止过多的SQL请求穿透到数据库

 * 用于解决PHP在并发时候的锁控制,通过文件/eaccelerator进行进程间锁定

 * 如果没有使用eaccelerator则进行进行文件锁处理,会做对应目录下产生对应粒度的锁

 * 使用了eaccelerator则在内存中处理,性能相对较高

 * 不同的锁之间并行执行,类似mysql innodb的行级锁

 * 本类在sunli的phplock的基础上做了少许修改  http://code.google.com/p/phplock

 * @author yangxinqi

 *

 */

class CacheLock

{

    //文件锁存放路径

    private $path = null;

    //文件句柄

    private $fp = null;

    //锁粒度,设置越大粒度越小

    private $hashNum = 100;

    //cache key

    private $name;

    //是否存在eaccelerator标志

    private  $eAccelerator = false;

 

    /**

     * 构造函数

     * 传入锁的存放路径,及cache key的名称,这样可以进行并发

     * @param string $path 锁的存放目录,以"/"结尾

     * @param string $name cache key

     */

    public function __construct($name,$path='lock\\')

    {

        //判断是否存在eAccelerator,这里启用了eAccelerator之后可以进行内存锁提高效率

        $this->eAccelerator = function_exists("eaccelerator_lock");

        if(!$this->eAccelerator)

        {

            if (!is_dir($path)) {

                mkdir($path, 0777);

            }

            $this->path = $path.($this->_mycrc32($name) % $this->hashNum).'.txt';

        }

        $this->name = $name;

    }

 

    /**

     * crc32

     * crc32封装

     * @param int $string

     * @return int

     */

    private function _mycrc32($string)

    {

        $crc = abs (crc32($string));

        if ($crc & 0x80000000) {

            $crc ^= 0xffffffff;

            $crc += 1;

        }

        return $crc;

    }

    /**

     * 加锁

     * Enter description here ...

     */

    public function lock()

    {

        //如果无法开启ea内存锁,则开启文件锁

        if(!$this->eAccelerator)

        {

            //配置目录权限可写

            $this->fp = fopen($this->path, 'w+');

            if($this->fp === false)

            {

                return false;

            }

            return flock($this->fp, LOCK_EX);

        }else{

            return eaccelerator_lock($this->name);

        }

    }

 

    /**

     * 解锁

     * Enter description here ...

     */

    public function unlock()

    {

        if(!$this->eAccelerator)

        {

            if($this->fp !== false)

            {

                flock($this->fp, LOCK_UN);

                clearstatcache();

            }

            //进行关闭

            fclose($this->fp);

        }else{

            return eaccelerator_unlock($this->name);

        }

    }

}

?>

Copy after login

?使用如下:

1

2

3

4

5

$lock = new CacheLock('key_name');

$lock->lock();

//logic here

$lock->unlock();

//使用过程中需要注意下文件锁所在路径需要有写权限.

Copy after login
Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What are the differences between Huawei GT3 Pro and GT4? What are the differences between Huawei GT3 Pro and GT4? Dec 29, 2023 pm 02:27 PM

Many users will choose the Huawei brand when choosing smart watches. Among them, Huawei GT3pro and GT4 are very popular choices. Many users are curious about the difference between Huawei GT3pro and GT4. Let’s introduce the two to you. . What are the differences between Huawei GT3pro and GT4? 1. Appearance GT4: 46mm and 41mm, the material is glass mirror + stainless steel body + high-resolution fiber back shell. GT3pro: 46.6mm and 42.9mm, the material is sapphire glass + titanium body/ceramic body + ceramic back shell 2. Healthy GT4: Using the latest Huawei Truseen5.5+ algorithm, the results will be more accurate. GT3pro: Added ECG electrocardiogram and blood vessel and safety

Fix: Snipping tool not working in Windows 11 Fix: Snipping tool not working in Windows 11 Aug 24, 2023 am 09:48 AM

Why Snipping Tool Not Working on Windows 11 Understanding the root cause of the problem can help find the right solution. Here are the top reasons why the Snipping Tool might not be working properly: Focus Assistant is On: This prevents the Snipping Tool from opening. Corrupted application: If the snipping tool crashes on launch, it might be corrupted. Outdated graphics drivers: Incompatible drivers may interfere with the snipping tool. Interference from other applications: Other running applications may conflict with the Snipping Tool. Certificate has expired: An error during the upgrade process may cause this issu simple solution. These are suitable for most users and do not require any special technical knowledge. 1. Update Windows and Microsoft Store apps

How to Fix Can't Connect to App Store Error on iPhone How to Fix Can't Connect to App Store Error on iPhone Jul 29, 2023 am 08:22 AM

Part 1: Initial Troubleshooting Steps Checking Apple’s System Status: Before delving into complex solutions, let’s start with the basics. The problem may not lie with your device; Apple's servers may be down. Visit Apple's System Status page to see if the AppStore is working properly. If there's a problem, all you can do is wait for Apple to fix it. Check your internet connection: Make sure you have a stable internet connection as the "Unable to connect to AppStore" issue can sometimes be attributed to a poor connection. Try switching between Wi-Fi and mobile data or resetting network settings (General > Reset > Reset Network Settings > Settings). Update your iOS version:

php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 php提交表单通过后,弹出的对话框怎样在当前页弹出,该如何解决 Jun 13, 2016 am 10:23 AM

php提交表单通过后,弹出的对话框怎样在当前页弹出php提交表单通过后,弹出的对话框怎样在当前页弹出而不是在空白页弹出?想实现这样的效果:而不是空白页弹出:------解决方案--------------------如果你的验证用PHP在后端,那么就用Ajax;仅供参考:HTML code

How to use Lock in Java multithreading How to use Lock in Java multithreading May 12, 2023 pm 02:46 PM

After Jdk1.5, under the java.util.concurrent.locks package, there is a set of interfaces and classes for thread synchronization. When it comes to thread synchronization, everyone may think of the synchronized keyword, which is a built-in keyword in Java. It handles thread synchronization, but this keyword has many flaws and is not very convenient and intuitive to use, so Lock appears. Below, we will compare and explain Lock. Usually when we use the synchronized keyword, we will encounter the following problems: (1) Uncontrollability, unable to lock and release locks at will. (2) The efficiency is relatively low. For example, we are currently reading two files concurrently.

Let's talk about why Vue2 can access properties in various options through this Let's talk about why Vue2 can access properties in various options through this Dec 08, 2022 pm 08:22 PM

This article will help you interpret the vue source code and introduce why you can use this to access properties in various options in Vue2. I hope it will be helpful to everyone!

An article that understands this point and catches up with 70% of front-end people An article that understands this point and catches up with 70% of front-end people Sep 06, 2022 pm 05:03 PM

A colleague got stuck due to a bug pointed by this. Vue2’s this pointing problem caused an arrow function to be used, resulting in the inability to get the corresponding props. He didn't know it when I introduced it to him, and then I deliberately looked at the front-end communication group. So far, at least 70% of front-end programmers still don't understand it. Today I will share with you this link. If everything is wrong If you haven’t learned it yet, please give me a big mouth.

What are the ways to use Lock in Java? What are the ways to use Lock in Java? Apr 23, 2023 pm 08:52 PM

1. Function (1) The Lock method to acquire locks supports interruption, no acquisition after timeout, and is non-blocking (2) It improves semantics. Where to lock and unlock must be written out (3) Lock explicit lock can bring us Comes with good flexibility, but at the same time we must manually release the lock (4) Support Condition condition object (5) Allow multiple reading threads to access shared resources at the same time 2.lock usage //Get the lock voidlock() //If the current thread has not If interrupted, acquire the lock voidlockInterruptibly()//Return a new Condition instance bound to this Lock instance ConditionnewCondition()//Lock only when called

See all articles