Search code examples
phpmultiprocessingforkpcntl

Unexpected cores synchronization in pcntl_fork()


I'm researching multi-core optimization abilities in PHP. My test program forks 4 processes so that each one should run twice as long as previous. Code is:

 $iters =  20000000;

 for ($c = 0; $c < 4; $c++) {

    $pid = pcntl_fork();

    if ($pid == 0) {

        for ($i=0; $i < $iters * (pow(2,$c)); $i++)
           $x = $i << 2;

        exit(0);
    }
 }

Now after looking at CPU cores load graph, i've noticed that 2 cores finishes job almost at the same time: enter image description here Sometimes even 3 cores tries to synchronize and their load falls approximately in the same time.

Question is - Why each one of cores not finishes job after twice as many time previous core needed according to PHP test script ? And why two cores finishes job almost at the same time ?

Machine specifications (lscpu output):

CPU(s): 4

On-line CPU(s) list: 0-3

Thread(s) per core: 2

Core(s) per socket: 2

Socket(s): 1

Can it be that this effect is related that test machine has only 2 real cores, so somehow this effect is related to hyper-threading ?


Solution

  • I've had chance to repeat experiment on machine with 4 physical cores. lscpu output about machine CPU specification:

    CPU(s): 4

    On-line CPU(s) list: 0-3

    Thread(s) per core: 1

    Core(s) per socket: 4

    Socket(s): 1

    And I've got such CPU load graph when running experiment: enter image description here

    So it can be seen that in this case there is no cross-core synchronization and each core is loaded with about twice as many work as previous one. Confirmed that above mentioned effect is related that test machine had 4 virtual cores (2 physical x 2 hyper-threads) and not just 4 physical ones.