Example of PHP file lock-based multi-process reading/writing a file at the same time,

Source: Internet
Author: User
Tags flock

Example of PHP file lock-based multi-process reading/writing a file at the same time,

This example describes how PHP solves the problem of multiple processes simultaneously reading and writing a file based on the file lock. We will share this with you for your reference. The details are as follows:

First, PHP supports processes rather than multithreading (this should be clarified first). For file operations, you only need to lock the files and do not need other operations, PHP flock has already been done for you.

Use flock to lock a file before writing it, and unlock it after writing it. This enables multiple threads to read and write a file at the same time to avoid conflicts. This is probably the process below.

/** Flock (file, lock, block) * file is required. It specifies that * lock is required for an opened file to be locked or released. Specifies the type of lock to be used. * Optional. If it is set to 1 or true, other processes are blocked when the lock is performed. * Lock * LOCK_SH to obtain the shared lock (read program) * LOCK_EX to obtain the exclusive lock (written Program) * LOCK_UN to release the lock (whether shared or exclusive) * LOCK_NB if you do not want flock () to be blocked at lock time/* if (flock ($ file, LOCK_EX) {fwrite ($ file, 'Write more word '); flock ($ file, LOCK_UN);} else {// handle error logic} fclose ($ file );)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.