Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example: Parallel processing in PHP using pcntl_fork()
<?php
/**
* @file
* Basic demonstration of how to do parallel threads in PHP.
*/
// This array of "tasks" could be anything. For demonstration purposes
// these are just strings, but they could be a callback, class or
// include file (hell, even code-as-a-string to pass to eval()).
$tasks = [
"fetch_remote_data",
"post_async_updates",
"clear_caches",
"notify_admin",
];
// This loop creates a new fork for each of the items in $tasks.
foreach ($tasks as $task) {
$pid = pcntl_fork();
if ($pid == -1) {
exit("Error forking...\n");
}
else if ($pid == 0) {
execute_task($task);
exit();
}
}
// This while loop holds the parent process until all the child threads
// are complete - at which point the script continues to execute.
while(pcntl_waitpid(0, $status) != -1);
// You could have more code here.
echo "Do stuff after all parallel execution is complete.\n";
/**
* Helper method to execute a task.
*/
function execute_task($task_id) {
echo "Starting task: ${task_id}\n";
// Simulate doing actual work with sleep().
$execution_time = rand(5, 10);
sleep($execution_time);
echo "Completed task: ${task_id}. Took ${execution_time} seconds.\n";
}
@ahmadmarafa

This comment has been minimized.

Copy link

commented Feb 15, 2018

Well explained , thank you

@fenriz07

This comment has been minimized.

Copy link

commented Feb 27, 2018

Nice

@harkalygergo

This comment has been minimized.

Copy link

commented Apr 30, 2018

First: thank you!
Is this stops after 99. on a 500+ task list just me?

@filmo

This comment has been minimized.

Copy link

commented May 22, 2018

Question. If a mysql resource is created in the scope of the parent process, can it be used in the child worker process? For example, if above line 17, you had created a $mysqli = new mysqli(...); would you be able to access that db handle inside the execute_task function either by 'global $mysqli' or by passing it in as a parameter to the execute_task function?

Great tutorial! Thanks.

@silasmagare

This comment has been minimized.

Copy link

commented Jul 13, 2018

fantastic

@SergioAraya

This comment has been minimized.

Copy link

commented Dec 29, 2018

muchas gracias muy útil el código

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.