php - 在 PHP 中同步和暂停线程

标签 php multithreading

我同时运行 2 个线程,但我有一个关键部分,我需要在 MySql 数据库中放置一些东西。问题是他们可以同时放入相同的东西。

我做了一些计算,表明要索引 20000 个不同的新闻页面,索引从 20000 到 20020。(所以 0 到 20 是重复的)

如何在另一个线程访问数据库时暂停一个线程?

-----thread.php
class Process extends Thread {

    public function __construct($website_url){
        $this->website_url = $website_url;
    }

    public function run() {
        work($this->website_url);
    }
}

-------------- work

function work($website_url) {
    while(condition) {
        some work...

        if(something->check){      // if this exist in base
            mysqli->query("INSERT something IN db..."); 
            prepare bind exec...
        }
        // between check and insert, second thread can put that element
        // critical section is really small but sometimes occurs ...
    }
}

------ main.php

$job1 = new Process($website_url,$trigger);
$job2 = new Process($website_url,$trigger);

$job1->start();
$job2->start();

最佳答案

互斥

在这里实现您想要的最简单方法是使用单个互斥体:

<?php
class Process extends Thread {

    public function __construct($url, $mutex) {
        $this->url = $url;
        $this->mutex = $mutex;
    }

    public function run() {
        work($this->url, $this->mutex);
    }

    protected $url;
    protected $mutex;
}

function work($url, $mutex) {
    while (1) {
        /* some work */

        /* failing to check the return value of calls to acquire
            or release mutex is bad form, I haven't done so for brevity */
        Mutex::lock($mutex);
        {
            /* critical section */
            printf("working on %s\n", $url);

            /* sleeping here shows you that the critical section is 
                not entered by the second thread, this is obviously not needed */
            sleep(1);
        }
        Mutex::unlock($mutex);

        /* breaking here allows the example code to end, not needed */
        break;
    }
}

$website = "stackoverflow.com";

$lock = Mutex::create();

$jobs = [
    new Process($website, $lock),
    new Process($website, $lock)
];

foreach ($jobs as $job)
    $job->start();

foreach ($jobs as $job)
    $job->join();

/* always destroy mutex when finished with them */    
Mutex::destroy($lock);
?>

这段代码应该可以自行解释,我添加了一些注释来指导您完成它。

关于php - 在 PHP 中同步和暂停线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25533965/

相关文章:

php - XMLHttpRequest 的问题

php - 如何使用 JMS Serializer 处理递归对象

.net - 并行GDI +图像调整大小.net

java - 仅对最新的异步更新数据运行计算

php - 通过 api 在 wordpress.com 中添加特色图片

php - 使用 CodeIgniter 进行自动化单元测试

multithreading - Erlang 的并发模型究竟是什么?

ios - Realm 不正确的线程访问崩溃

php - 而 mysql_fetch_assoc 到数组

java - 实现连续线程的高效方式