Skip to content

Latest commit

 

History

History
144 lines (102 loc) · 5.19 KB

1.Main.md

File metadata and controls

144 lines (102 loc) · 5.19 KB

Basic information


  1. Basic information about the thread
  2. Simplified thread creation with closures
  3. Basic information about the thread pool

1 - Basic information about the thread

Instance of class Thread inheritor represents "thread". It's forkes parent process and allows parallel calculations in the two processes. Communication between processes is supported by a pair of sockets, using an effective "event loop" model.

Thread can also work in compatibility mode - with no real parallel, forks and "event loop". Just in case there no dependencies or for testing. To force the inclusion of this mode, set the property Thread::$useForks to false.

For work you need to override the method process - code in it will be called asynchronously.

class ExampleThread extends Thread
{
	function process()
	{
		// Code executed asynchronously
	}
}

Arguments for the job can be obtained via the methods getParam, getParams. Arguments are passed as with a usual function when you call the method run. With the option $argumentsMapping you can enable the arguments mapping as in a usual function, but it slows down a bit and therefore is disabled by default.

class ExampleThread extends Thread
{
	function process()
	{
		// First parameter
		echo $this->getParam(0); // 12
		// Second parameter
		echo $this->getParam(1); // 79
		// Array with all parameters
		$params = $this->getParams();
	}
}
$thread = new ExampleThread();
$thread->wait()->run(12, 79);

Results can be sent via usual return and obtained by using the method getResult:

class ExampleThread extends Thread
{
	function process()
	{
		return 123;
	}
}
$thread = new ExampleThread();
echo $thread->wait()->run()->wait()->getResult(); // 123

wait method is used to synchronize in the child and the parent process - it runs the "event loop", in which data is transferred from the parent process to the child and vice versa.

You need to call method wait once after creating the instance of "thread" and before running the task. You can disable this behavior by enabling the option $preforkWait so waiting for initialization will happen automatically, but more efficient not to do it.

More information about the configuration options for the thread can be found in the relevant part of the documentation.

getSuccess method lets you know if last task is ended successfully or not. If the task fails, you can get error code using the getLastErrorCode() and the error text using getLastErrorMsg().

Highly recommened to explicitly free all resources after work to avoid any leaks:

$thread->cleanup();

2 - Simplified thread creation with closures

You can create threads even easier - from the closures, using the SimpleThread class. Such threads are not preforked by default and not multitask too. You can change it via the second argument of SimpleThread::create.

Arguments in threads-closures are always mapped as in usual functions.

$result = SimpleThread::create(function($arg) {
	return $arg;
})->run(123)->wait()->getResult();

Since PHP 5.4.0 $this can be used in anonymous functions, as in a regular thread (more info).

3 - Basic information about the thread pool

The thread pool can be created using the ThreadPool class.

$pool = new ThreadPool(
	'ExampleThread', // The full thread class name
	8                // Number of threads
);

Pool allows efficiently and conveniently distribute tasks among multiple threads and receive the results, events from the threads. In general, it's effective to use the number of threads as the number of processor cores, but to achieve greater efficiencies you can choose it on the specific system experimentally.

Three methods are used for the basic work with a pool: hasWaiting, run, wait.

while ($pool->hasWaiting()) {
	$threadId = $pool->run();
	// ...
}
if ($results = $pool->wait($failed)) {
	foreach ($results as $threadId => $result) {
		// ...
	}
}
if ($failed) {
	foreach ($failed as $threadId => $err) {
		list($errorCode, $errorMessage) = $err;
		// ...
	}
}

hasWaiting tells if there are free threads in the pool. In the free thread you can start the task using the run method. It accepts parameters for the task and returns the ID of the thread that started processing of the task.

Results can be retrieved with the wait method. It runs the event loop, waiting for the results and returns an array of successful results. An array of errors from tasks can be received by reference via the first argument of the wait method. Each error includes an error code and an explanatory text.

You can identify successful and unsuccessful results by using the thread ID.

Highly recommened to explicitly free all resources after work to avoid any leaks:

$pool->cleanup();

A complete example of using the pool with error handling can be found among other examples.