How to implement PHP multithreading concurrency

Source: Internet
Author: User
Tags php multithreading sleep


In Java, multithreading is a new thread of things, PHP relies on the Apache Linux Bottom has a multithreaded approach.

Tell me today if you can't manipulate Apache servers, how to simulate PHP concurrency

<?php
if (function_exists (' Date_default_timezone_set ')) {
Date_default_timezone_set (' PRC ');
}

function A ()
{
$time = time ();

Sleep (3);
$fp = fopen (' result_a '. $time. Log ', ' W ');
Fputs ($fp, ' Set in '. Date (' H:i:s ', Time ()). (double) microtime (). "RN");
Fclose ($FP);
}
Function B ()
{
$time = time ();

Sleep (3);
$fp = fopen (' Result_b '. $time. Log ', ' W ');
Fputs ($fp, ' Set in '. Date (' H:i:s ', Time ()). (double) microtime (). "RN");
Fclose ($FP);
}

if (!isset ($_get[' act ')) $_get[' act ' = ' a ';

if ($_get[' act '] = = ' a ')
{
A ();
}
else if ($_get[' act '] = = ' B ') b ();
?>
The above code to write a file locally.
If you access localhost/a.php the two browser tabs open as fast as possible, you find that two file creation time is 3 seconds

But if you visit localhost/a.php?act=b another visit to/a.php?act=a you find that two files are created almost the same time.

For Apache, the same URL means a thread (we or a process), but a different URL means that it can be concurrent.

If there is a download action inside PHP

function Runthread ()
{
Down ("Http://localhost/test/a.php?act=a");
}
if ($_get[' act '] = = ' Run ')
{
Echo ' Start: ';

Runthread ();

echo ' End ';
}
Http://localhost/test/a.php?act=run

http://localhost/test/a.php?act=run&s=2

As long as the URL of the primary access is different, it is considered to be different, meaning concurrency. File creation time is not 3 seconds

A friend with a local Linux server can also use Linux to simulate concurrency.

<?php
For ($i =0 $i <10; $i + +) {
echo $i;
Sleep (5);
}
?>
Save it as a test.php, then write a shell code

#!/bin/bash
For I in 1 2 3 4 5 6 7 8 9 10
Todo
Php-q test.php &
Done

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.