📜 ⬆️ ⬇️

phpThread: threads in php? Easily

If you want to learn how to write multithreaded PHP applications or great to simplify your life - the article is for you.

I used to use several copies of the script for this purpose, or used pcntl at a lower level than I would like. This, and in part the Java ideology of working with threads, prompted me to write the phpThread package.

So:
<?php
include 'thread.class.php' ;
include 'threadCollection.class.php' ;
class MyThread extends Thread
{
public function run()
{
for (;;)
{
echo date( 'r' ). "\n" ;
if (!$ this ->sleep(2)) { return ;}
}
}
}
echo "Starting...\n" ;
$threads = new threadCollection;
for ($i = 0; $i < 5; ++$i) {$threads->push( new MyThread);}
$threads->start();
echo "Doing pseudo-job (sleep for 5 seconds)...\n" ;
sleep(5);
echo "Pseudo-job in master done. Stopping and waiting...\n" ;
$threads->stop();
$threads->wait();

* This source code was highlighted with Source Code Highlighter .
This uncomplicated code creates 5 children, waits 5 seconds, and then stops them.

You can pick it up here - code.google.com/p/phpthread
The project is written literally on the knee, but it works great.
At the moment, the source code weighs 1,247 bytes.
In the near future - to make convenient work with competitive storage.
')
This technique should be used:

1. When the program is not fast enough to receive data and increased idle time. For example, when generating beautiful graphics, one stream can receive data from a DBMS (a heavy query is executed), and in the second stream it is possible to draw.

2. When you need to perform multiple operational tasks, and more efficiently utilize the processor.

I will be glad to any feedback, ideas, and comments.

Thanks for attention.

Source: https://habr.com/ru/post/59982/


All Articles