当我们用多线程操作同一个资源时,在同一时间内只能有一个线程能够对资源进行操作,这时就需要用到互斥量了。比如我们对同一个文件进行读写操作时。
当第一个线程给互斥量加锁后,如果在操作期间,其他线程再次给互斥量加锁,会导致线程进入阻塞状态,直到互斥量被解锁。这就很好的保护了文件在同一时间内只能被一个线程操作。
<?php class Add extends Thread { private $name = ''; private $res = null; private $mutex = null; public function __construct($name, $res, $mutex = null) { $this->name = $name; $this->res = $res; $this->mutex = $mutex; } public function run() { if($this->mutex) { //给互斥量加锁 Mutex::lock($this->mutex); } //从文件中获取数据 $data = trim(fgets($this->res)); $data = intval($data); ++$data; //重置文件指针到开始处 fseek($this->res, 0); //写入数据 fwrite($this->res, $data); //重置文件指针 fseek($this->res, 0); echo "Thread {$this->name} add {$data} "; if($this->mutex) { //给互斥量解锁 Mutex::unlock($this->mutex); } } } $fp = fopen('./add.txt', 'r+'); //创建互斥量,立即加锁 $mutex = Mutex::create(true); $threads = array(); for($ix = 0; $ix < 20; ++$ix) { $thread = new Add($ix, $fp, $mutex); $thread->start(); $threads[] = $thread; } Mutex::unlock($mutex); foreach($threads as $thread) { $thread->join(); } //销毁互斥量 Mutex::destroy($mutex);
如果不加锁,那么对文件的操作结果是不可预知的,因为同一时间内有很多线程同时操作文件,无法判断先后顺序。