You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP多线程开发求助:如何并行执行三个线程?

Fixing Parallel Thread Execution in PHP

Hey there! Let's get your three threads running in parallel properly. I noticed a few key issues in your code that are blocking parallel execution—let's break them down and fix them step by step:

Key Issues in Your Original Code

  • Calling run() directly: The run() method executes in the current thread, not a new parallel thread. To spawn a separate thread, you need to use start() instead.
  • Missing thread synchronization: You didn’t wait for threads to finish before trying to access their results. Use join() to make the main thread pause until each worker thread completes.
  • Syntax errors: Your echo statements have missing concatenation dots before <br/>, which will throw errors.
  • Sequential result overwriting: You’re overwriting $_set one after another, which defeats the purpose of parallelism. Instead, you need to collect results from each thread individually.
  • Potential race conditions: If threads share the same data without safeguards, you’ll get unpredictable results. We’ll ensure each thread works with its own copy of the data.

Corrected Code Example

First, make sure you have the pthreads extension installed (it’s required for PHP thread support). Here’s the fixed code:

<?php
$set = "abcacbabccbacab";
$_set = $set;
echo "S = {" . $_set . "}<br/>";

// Create thread instances, each gets its own copy of the original set
$rule1 = new Rule1($_set);
$rule2 = new Rule2($_set);
$rule3 = new Rule3($_set);

// Start all threads in parallel
$rule1->start();
$rule2->start();
$rule3->start();

// Wait for all threads to finish execution before collecting results
$rule1->join();
$rule2->join();
$rule3->join();

// Retrieve results from each thread
$result1 = $rule1->result;
$result2 = $rule2->result;
$result3 = $rule3->result;

// Output results (adjust how you combine them based on your needs)
echo "Rule1 Result: {" . $result1 . "}<br/>";
echo "Rule2 Result: {" . $result2 . "}<br/>";
echo "Rule3 Result: {" . $result3 . "}<br/><br/>";

// Thread classes with result storage
class Rule1 extends Thread {
    public $set;
    public $result;

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

    public function run() {
        // Replace with your actual Rule1 logic
        // Example: Reverse the input string
        $this->result = strrev($this->set);
    }
}

class Rule2 extends Thread {
    public $set;
    public $result;

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

    public function run() {
        // Replace with your actual Rule2 logic
        // Example: Count number of 'a's in the string
        $this->result = substr_count($this->set, 'a');
    }
}

class Rule3 extends Thread {
    public $set;
    public $result;

    public function run() {
        // Replace with your actual Rule3 logic
        // Example: Convert string to uppercase
        $this->result = strtoupper($this->set);
    }
}
?>

Explanation of Changes

  1. Thread Initialization: Each rule thread gets its own copy of the original $set to avoid race conditions where threads overwrite each other’s data.
  2. Starting Threads: start() launches each thread in parallel, so they run at the same time instead of one after another.
  3. Joining Threads: join() ensures the main thread waits for all worker threads to finish before accessing their results—this prevents trying to read data that hasn’t been generated yet.
  4. Result Storage: Each thread stores its output in a public $result property, which we can safely access after the thread finishes.
  5. Syntax Fixes: Corrected the echo statements to properly concatenate HTML elements.

If You Need to Modify Shared Data

If your rules need to update a shared dataset (instead of working independently), you’ll need synchronization tools like Mutex to prevent race conditions. Here’s a quick example of a thread-safe shared data class:

class SharedData extends Threaded {
    public $data;
    protected $mutex;

    public function __construct($data) {
        $this->data = $data;
        $this->mutex = Mutex::create();
    }

    public function applyRule($ruleType) {
        Mutex::lock($this->mutex);
        // Perform safe, synchronized modifications here
        switch($ruleType) {
            case 'rule1':
                $this->data = strrev($this->data);
                break;
            // Add other rule logic here
        }
        Mutex::unlock($this->mutex);
    }

    public function __destruct() {
        Mutex::destroy($this->mutex);
    }
}

You’d pass this SharedData instance to each thread, and threads would call applyRule() instead of directly modifying the data.

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 02:33:27