2017-07-02 27 views
1

我想在php中使用pthread來並行執行一些任務。我在上安裝了pthread,win10,我剛剛從網站上覆制了一些例子,但所有這些例子都是順序而不是並行的!從http://www.smddzcy.com/2016/01/tutorial-multi-threading-in-php7-pthreads/ 一個例子:爲什麼PHP線程在我的本地主機上連續不平行?

<?php 

class SomeThreadedClass extends Thread 
{ 
    private $tID; 
    public $data; 

    public function __construct(int $tID) 
    { 
     $this->tID = $tID; 
     $this->data = $tID . ":" . date('H:i:s'); 
    } 

    public function run() 
    { 
     echo $this->tID . " started.\n"; 
     sleep($this->tID); 
     echo $this->tID . " ended. " . date('H:i:s') . "\n"; 
    } 
} 

$threads = []; 

for ($i = 1; $i < 5; $i++) { 
    $threads[$i] = new SomeThreadedClass($i); 
    $threads[$i]->start();   // start the job on the background 
} 

for ($i = 1; $i < 5; $i++) { 
    $threads[$i]->join();   // wait until job is finished, 
    echo $threads[$i]->data . "\n"; // then we can access the data 
} 

網站上的結果是:

1 started. 
2 started. 
3 started. 
4 started. 
1 ended. 18:18:52 
1:18:18:51 
2 ended. 18:18:53 
2:18:18:51 
3 ended. 18:18:54 
3:18:18:51 
4 ended. 18:18:55 
4:18:18:51 

當我運行在我的本地代碼,我得到這樣的結果:

1 started. 
1 ended. 13:11:24 
2 started. 
2 ended. 13:11:25 
3 started. 3 ended. 13:11:26 
4 started. 4 ended. 13:11:27 
1:15:41:23 
2:15:41:23 
3:15:41:23 
4:15:41:23 

爲什麼線程在本地主機上是順序不平行的?

+0

也許擴展不能很好地工作在windows上看起來像教程是基於一臺MaC電腦。 –

+0

@RaymondNijland我查看了其他網站上的許多其他例子,他們都有一個序列結果。 – hodhod

回答

2

線程並行執行。您可以通過查看正在輸出的時間來判斷。所有線程同時開始,並且每個線程在每個連接線程之間僅完成1秒。考慮到sleep時間在每個新線程正在產生時遞增,如果它們按順序執行,則每個線程結束之間的時間間隔將遞增。

例如,改變線程產卵,並加入您的腳本的一部分以下(強制順序執行):

1 started. 
1 ended. 15:14:06 
1:15:14:05 
2 started. 
2 ended. 15:14:08 
2:15:14:06 
3 started. 
3 ended. 15:14:11 
3:15:14:08 
4 started. 
4 ended. 15:14:15 
4:15:14:11 

注意不同:

for ($i = 1; $i < 5; $i++) { 
    $threads[$i] = new SomeThreadedClass($i); 
    $threads[$i]->start();   // start the job on the background 
    $threads[$i]->join();   // wait until job is finished, 
    echo $threads[$i]->data . "\n"; // then we can access the data 
} 

將輸出類似的東西開始時間和完成時間之間的增量差距。至於爲什麼你按照這個順序接收到輸出,它就是輸出緩衝區如何處理多個線程的輸出。我的輸出是不同的,但後來我使用OS X.

相關問題