├── CHANGELOG.md ├── CODE_OF_CONDUCT.md ├── Dockerfile ├── LICENSE ├── README.md ├── composer.json ├── phpcs.xml ├── phpstan.neon └── src ├── AdapterInterface.php ├── Exception.php ├── Fork.php ├── Interfaces └── ForkInterface.php ├── PcntlAdapter.php ├── SharedMemory.php ├── SingleThreadAdapter.php └── Threads.php /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | Changelog 2 | ========= 3 | 4 | ## x.y.z - UNRELEASED 5 | 6 | -------- 7 | 8 | ## 2.5.0 - 2024-07-29 9 | 10 | ### Changed 11 | 12 | * [Support] Added support for PHP 8.1, 8.2, and 8.3. 13 | 14 | -------- 15 | 16 | ## 2.4.0 - 2021-08-15 17 | 18 | ### Changed 19 | 20 | * [Support] Added support for PHP 7.4 and 8.0 21 | * [Support] Dropped support for PHP 7.1, 7.2, and 7.3. 22 | 23 | -------- 24 | 25 | ## 2.3.0 - 2019-01-10 26 | 27 | ### Added 28 | 29 | * [Threads] A new class to allow a maximum number of threads to be used. 30 | * [Forking] An `isRunning()` method to check if a child process is running or not. 31 | * [ForkInterface] Created an interface for the main `Fork` class. 32 | 33 | ### Changed 34 | 35 | * [Support] Added support for PHP 7.2 and 7.3. 36 | * [Support] Dropped support for PHP 7.0. 37 | 38 | -------- 39 | 40 | ## 2.2.1 - 2018-08-22 41 | 42 | ### Fixed 43 | 44 | * [SharedMemory] Fix shared memory allocation [#10](https://github.com/duncan3dc/fork-helper/pull/10). 45 | 46 | -------- 47 | 48 | ## 2.2.0 - 2017-07-11 49 | 50 | ### Changed 51 | 52 | * [Forking] You MUST call wait() now, it's not safe to rely on the destructor. 53 | 54 | ### Fixed 55 | 56 | * [SharedMemory] Ensure memory is deleted when we're finished. 57 | 58 | -------- 59 | 60 | ## 2.1.0 - 2017-03-04 61 | 62 | ### Added 63 | 64 | * [Forking] Made the wait() method chainable. 65 | 66 | ### Fixed 67 | 68 | * [SharedMemory] Avoid creating two instances for the same memory. 69 | * [Exceptions] Allow more exceptions to be added after initial retrieval. 70 | 71 | -------- 72 | 73 | ## 2.0.0 - 2016-10-16 74 | 75 | ### Added 76 | 77 | * [Forking] Allow code to be executed even if pcntl isn't available. 78 | * [Forking] Allow any adapter to be used to handle code execution. 79 | * [Support] Added support for PHP 7.0 and 7.1. 80 | 81 | ### Fixed 82 | 83 | * [Exceptions] Catch the new \Throwable type to handle engine exceptions. 84 | 85 | ### Changed 86 | 87 | * [Namespace] Moved from \duncan3dc\Helpers to \duncan3dc\Forker to avoid clashes with other helpers. 88 | * [Forking] The call() method now accepts variadic arguments. 89 | * [Exceptions] Throw a more specific Exception (\duncan3dc\Forker\Exception) when things go wrong. 90 | * [Exceptions] Removed the $ignoreErrors feature in favour of calling code catching the exception. 91 | * [Support] Dropped support for PHP 5. 92 | 93 | -------- 94 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | This code of conduct outlines our expectations for participants within the open source community. Anyone who violates this code of conduct may be banned from contributing here. 2 | 3 | # Requirements 4 | * __Be friendly and patient.__ 5 | * __Be welcoming__ _We strive to be a community that welcomes and supports people of all backgrounds and identities._ 6 | * __Be respectful__ _Not all of us will agree all the time, but disagreement is no excuse for poor behavior and poor manners._ 7 | 8 | # Unacceptable Behaviour 9 | * Offensive comments related to gender, sexual orientation, disability, mental illness, physical appearance, body size, race, age, regional discrimination, political or religious affiliation. 10 | * Threats of violence, both physical and psycological. 11 | * Incitement of violence towards any individual, including encouraging a person to commit suicide or to engage in self-harm. 12 | * Continued communication after requests to cease. 13 | 14 | # Interactions 15 | * Don't just tell somebody they are wrong, or what they have done is wrong. You must always explain what is wrong, and why it is wrong. 16 | * Don't reject contributions that are partially complete and then go and commit your own version. Try to work with the author to complete their work. 17 | * We encourage everyone to participate and are committed to building a community for all, we seek to treat everyone both as fairly and equally as possible. 18 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | ARG PHP_VERSION=7.2 2 | FROM php:${PHP_VERSION}-cli 3 | 4 | RUN docker-php-ext-install pcntl shmop 5 | 6 | ARG COVERAGE 7 | RUN if [ "$COVERAGE" = "pcov" ]; then pecl install pcov && docker-php-ext-enable pcov; fi 8 | 9 | # Install composer to manage PHP dependencies 10 | RUN apt-get update && apt-get install -y git zip 11 | RUN curl https://getcomposer.org/download/1.9.1/composer.phar -o /usr/local/sbin/composer 12 | RUN chmod +x /usr/local/sbin/composer 13 | RUN composer self-update 14 | 15 | WORKDIR /app 16 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | fork-helper 2 | =========== 3 | 4 | Simple class to fork processes in PHP and allow multi-threading. 5 | 6 | Full documentation is available at https://duncan3dc.github.io/fork-helper/ 7 | PHPDoc API documentation is also available at [https://duncan3dc.github.io/fork-helper/api/](https://duncan3dc.github.io/fork-helper/api/namespaces/duncan3dc.Forker.html) 8 | 9 | [![release](https://poser.pugx.org/duncan3dc/fork-helper/version.svg)](https://packagist.org/packages/duncan3dc/fork-helper) 10 | [![build](https://github.com/duncan3dc/fork-helper/workflows/buildcheck/badge.svg?branch=main)](https://github.com/duncan3dc/fork-helper/actions?query=branch%3Amain+workflow%3Abuildcheck) 11 | [![coverage](https://codecov.io/gh/duncan3dc/fork-helper/graph/badge.svg)](https://codecov.io/gh/duncan3dc/fork-helper) 12 | 13 | 14 | Quick Example 15 | ------------- 16 | 17 | Run some code asynchronously: 18 | ```php 19 | $fork = new \duncan3dc\Forker\Fork; 20 | 21 | $fork->call(function () { 22 | for ($i = 1; $i <= 3; $i++) { 23 | echo "Process A - " . $i . "\n"; 24 | sleep(1); 25 | } 26 | }); 27 | $fork->call(function () { 28 | for ($i = 1; $i < 3; $i++) { 29 | echo "Process B - " . $i . "\n"; 30 | sleep(1); 31 | } 32 | }); 33 | 34 | sleep(1); 35 | echo "Waiting for the threads to finish...\n"; 36 | $fork->wait(); 37 | echo "End\n"; 38 | ``` 39 | 40 | _Read more at https://duncan3dc.github.io/fork-helper/_ 41 | 42 | 43 | Changelog 44 | --------- 45 | A [Changelog](CHANGELOG.md) has been available since version 2.0.0 46 | 47 | 48 | Where to get help 49 | ----------------- 50 | Found a bug? Got a question? Just not sure how something works? 51 | Please [create an issue](https//github.com/duncan3dc/fork-helper/issues) and I'll do my best to help out. 52 | Alternatively you can catch me on [Twitter](https://twitter.com/duncan3dc) 53 | 54 | 55 | ## duncan3dc/fork-helper for enterprise 56 | 57 | Available as part of the Tidelift Subscription 58 | 59 | The maintainers of duncan3dc/fork-helper and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/packagist-duncan3dc-fork-helper?utm_source=packagist-duncan3dc-fork-helper&utm_medium=referral&utm_campaign=readme) 60 | -------------------------------------------------------------------------------- /composer.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "duncan3dc/fork-helper", 3 | "type": "library", 4 | "description": "Simple class to fork processes in PHP and allow multi-threading", 5 | "keywords": ["fork","process","control","pcntl","multi-threading"], 6 | "homepage": "https://github.com/duncan3dc/fork-helper", 7 | "license": "Apache-2.0", 8 | "authors": [{ 9 | "name": "Craig Duncan", 10 | "email": "git@duncanc.co.uk", 11 | "homepage": "https://github.com/duncan3dc", 12 | "role": "Developer" 13 | }], 14 | "require": { 15 | "php": "^7.4 || ^8.0" 16 | }, 17 | "suggest": { 18 | "ext-pcntl": "Needed to allow multi-threaded execution of code", 19 | "ext-shmop": "If pcntl is present then shmop is required to handle errors" 20 | }, 21 | "require-dev": { 22 | "duncan3dc/object-intruder": "^1.0", 23 | "mockery/mockery": "^1.4", 24 | "phpstan/phpstan": "^0.12.94", 25 | "phpstan/phpstan-mockery": "^0.12.14", 26 | "phpstan/phpstan-phpunit": "^0.12.22", 27 | "squizlabs/php_codesniffer": "^3.6", 28 | "phpunit/phpunit": "^8.5.39" 29 | }, 30 | "autoload": { 31 | "psr-4": {"duncan3dc\\Forker\\": "src/"} 32 | }, 33 | "autoload-dev": { 34 | "psr-4": {"duncan3dc\\ForkerTests\\": "tests/"} 35 | }, 36 | "scripts": { 37 | "test": [ 38 | "vendor/bin/phpunit", 39 | "vendor/bin/phpstan analyse --level=max src tests", 40 | "vendor/bin/phpcs --standard=phpcs.xml src tests", 41 | "@composer validate --strict" 42 | ] 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /phpcs.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | src 5 | tests 6 | 7 | 8 | 9 | 10 | 11 | 12 | 0 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /phpstan.neon: -------------------------------------------------------------------------------- 1 | parameters: 2 | reportUnmatchedIgnoredErrors: false 3 | ignoreErrors: 4 | - '/^Access to an undefined property duncan3dc\\ObjectIntruder\\Intruder::/' 5 | - '/^Call to an undefined method duncan3dc\\ObjectIntruder\\Intruder::/' 6 | - '/expects Shmop, resource\|Shmop given\.$/' 7 | - '/expects resource, resource\|Shmop given\.$/' 8 | - '/^Method duncan3dc\\Forker\\SharedMemory::getMemory\(\) never returns resource so it can be removed from the return typehint\.$/' 9 | - '/^Method duncan3dc\\Forker\\SharedMemory::getMemory\(\) never returns Shmop so it can be removed from the return typehint\.$/' 10 | - '/has invalid (typehint )?type Shmop\.$/' 11 | 12 | includes: 13 | - vendor/phpstan/phpstan-mockery/extension.neon 14 | - vendor/phpstan/phpstan-phpunit/extension.neon 15 | -------------------------------------------------------------------------------- /src/AdapterInterface.php: -------------------------------------------------------------------------------- 1 | $threads The threads created. 19 | */ 20 | private $threads = []; 21 | 22 | 23 | /** 24 | * Create a container to run multiple threads. 25 | * 26 | * @param AdapterInterface $adapter The adapter to use to handle the threading 27 | */ 28 | public function __construct(AdapterInterface $adapter = null) 29 | { 30 | if ($adapter === null) { 31 | if (function_exists("pcntl_fork")) { 32 | $adapter = new PcntlAdapter(); 33 | } else { 34 | $adapter = new SingleThreadAdapter(); 35 | } 36 | } 37 | 38 | $this->adapter = $adapter; 39 | } 40 | 41 | 42 | /** 43 | * @inheritdoc 44 | */ 45 | public function call(callable $func, ...$args): int 46 | { 47 | $pid = $this->adapter->call($func, ...$args); 48 | 49 | $this->threads[$pid] = $pid; 50 | 51 | return $pid; 52 | } 53 | 54 | 55 | /** 56 | * @inheritdoc 57 | */ 58 | public function isRunning(int $pid): bool 59 | { 60 | if (!array_key_exists($pid, $this->threads)) { 61 | return false; 62 | } 63 | 64 | $running = $this->adapter->isRunning($pid); 65 | 66 | if (!$running) { 67 | unset($this->threads[$pid]); 68 | } 69 | 70 | return $running; 71 | } 72 | 73 | 74 | /** 75 | * @inheritdoc 76 | */ 77 | public function wait(int $pid = null): ForkInterface 78 | { 79 | if ($pid) { 80 | $threads = [$pid]; 81 | } else { 82 | $threads = $this->threads; 83 | } 84 | 85 | $error = 0; 86 | $status = 0; 87 | foreach ($threads as $pid) { 88 | $status = $this->adapter->wait($pid); 89 | if ($status > 0) { 90 | $error = $status; 91 | } 92 | unset($this->threads[$pid]); 93 | } 94 | 95 | if ($error !== 0) { 96 | $exceptions = $this->adapter->getExceptions(); 97 | 98 | $message = "An error occurred within a thread, the return code was: {$error}\n"; 99 | foreach ($exceptions as $exception) { 100 | $message .= " - {$exception}\n"; 101 | } 102 | 103 | $this->adapter->cleanup(); 104 | throw new Exception($message, $error); 105 | } 106 | 107 | $this->adapter->cleanup(); 108 | return $this; 109 | } 110 | 111 | 112 | /** 113 | * @inheritdoc 114 | */ 115 | public function getPIDs(): array 116 | { 117 | return array_values($this->threads); 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/Interfaces/ForkInterface.php: -------------------------------------------------------------------------------- 1 | allocateMemory(); 28 | $pid = pcntl_fork(); 29 | 30 | if ($pid == -1) { 31 | throw new Exception("Failed to fork"); 32 | } 33 | 34 | # If the child process was started then return its pid 35 | if ($pid) { 36 | return $pid; 37 | } 38 | 39 | # If this is the child process, then run the requested function 40 | try { 41 | $func(...$args); 42 | } catch (\Throwable $e) { 43 | $memory->addException($e); 44 | exit(1); 45 | } 46 | 47 | # Then we must exit or else we will end up the child process running the parent processes code 48 | die(); 49 | } 50 | 51 | 52 | /** 53 | * @inheritdoc 54 | */ 55 | public function isRunning(int $pid): bool 56 | { 57 | $result = pcntl_waitpid($pid, $status, \WNOHANG); 58 | 59 | return ($result === 0); 60 | } 61 | 62 | 63 | /** 64 | * Wait for the a thread started via call() to end. 65 | * 66 | * @param int $pid The pid to wait for 67 | * 68 | * @return int The exit code of the thread 69 | */ 70 | public function wait(int $pid): int 71 | { 72 | $status = 0; 73 | 74 | pcntl_waitpid($pid, $status); 75 | 76 | return $status; 77 | } 78 | 79 | 80 | /** 81 | * Get any exceptions thrown by the threads. 82 | * 83 | * @return \Throwable[] 84 | */ 85 | public function getExceptions(): array 86 | { 87 | if (!$this->memory) { 88 | return []; 89 | } 90 | 91 | return $this->memory->getExceptions(); 92 | } 93 | 94 | 95 | /** 96 | * Method to be called when the adapter is finished with. 97 | * 98 | * @return void 99 | * @throws \LogicException 100 | */ 101 | public function cleanup() 102 | { 103 | if (!$this->memory) { 104 | throw new \LogicException("Cleanup should be used after allocate."); 105 | } 106 | 107 | $this->memory->delete(); 108 | $this->memory = null; 109 | } 110 | 111 | private function allocateMemory(): SharedMemory 112 | { 113 | if (!$this->memory) { 114 | $this->memory = new SharedMemory(); 115 | } 116 | 117 | return $this->memory; 118 | } 119 | } 120 | -------------------------------------------------------------------------------- /src/SharedMemory.php: -------------------------------------------------------------------------------- 1 | key = (int) (microtime(true) * 1000); 30 | 31 | # Initialise the memory 32 | $memory = $this->getMemory(); 33 | shmop_write($memory, serialize([]), 0); 34 | if (version_compare(PHP_VERSION, '8.0.0', '<')) { 35 | shmop_close($memory); 36 | } 37 | } 38 | 39 | 40 | /** 41 | * Get the shared memory segment. 42 | * 43 | * @return \Shmop|resource 44 | */ 45 | private function getMemory() 46 | { 47 | $memory = shmop_open($this->key, "c", 0644, self::LIMIT); 48 | 49 | if (!$memory) { 50 | throw new Exception("Unable to open the shared memory block"); 51 | } 52 | 53 | return $memory; 54 | } 55 | 56 | 57 | /** 58 | * Get the exception details out of shared memory. 59 | * 60 | * @param \Shmop|resource $memory The shmop resource from shmop_open() 61 | * 62 | * @return \Throwable[] 63 | */ 64 | private function unserialize($memory): array 65 | { 66 | $data = shmop_read($memory, 0, self::LIMIT); 67 | $data = rtrim($data); 68 | 69 | $exceptions = unserialize($data); 70 | 71 | if (!is_array($exceptions)) { 72 | $exceptions = []; 73 | } 74 | 75 | return $exceptions; 76 | } 77 | 78 | 79 | /** 80 | * Add an exception the shared memory. 81 | * 82 | * @param \Throwable $exception The exception instance to add 83 | * 84 | * @return void 85 | */ 86 | public function addException(\Throwable $exception) 87 | { 88 | $memory = $this->getMemory(); 89 | 90 | $exceptions = $this->unserialize($memory); 91 | 92 | $exceptions[] = get_class($exception) . ": " . $exception->getMessage() . " (" . $exception->getFile() . ":" . $exception->getLine() . ")"; 93 | 94 | $data = serialize($exceptions); 95 | 96 | shmop_write($memory, str_repeat("\0", self::LIMIT), 0); 97 | shmop_write($memory, $data, 0); 98 | if (version_compare(PHP_VERSION, '8.0.0', '<')) { 99 | shmop_close($memory); 100 | } 101 | } 102 | 103 | 104 | /** 105 | * Get all the exceptions added to the shared memory. 106 | * 107 | * @return \Throwable[] 108 | */ 109 | public function getExceptions(): array 110 | { 111 | $memory = $this->getMemory(); 112 | 113 | $exceptions = $this->unserialize($memory); 114 | 115 | shmop_write($memory, str_repeat("\0", self::LIMIT), 0); 116 | shmop_write($memory, serialize([]), 0); 117 | 118 | if (version_compare(PHP_VERSION, '8.0.0', '<')) { 119 | shmop_close($memory); 120 | } 121 | 122 | return $exceptions; 123 | } 124 | 125 | 126 | /** 127 | * Delete the shared memory this instance represents. 128 | * 129 | * @return void 130 | */ 131 | public function delete() 132 | { 133 | $memory = shmop_open($this->key, "a", 0, 0); 134 | if ($memory) { 135 | shmop_delete($memory); 136 | if (version_compare(PHP_VERSION, '8.0.0', '<')) { 137 | shmop_close($memory); 138 | } 139 | } 140 | } 141 | } 142 | -------------------------------------------------------------------------------- /src/SingleThreadAdapter.php: -------------------------------------------------------------------------------- 1 | pid; 37 | 38 | $this->status[$pid] = 0; 39 | 40 | try { 41 | $func(...$args); 42 | } catch (\Throwable $e) { 43 | $this->exceptions[] = $e; 44 | $this->status[$pid] = 256; 45 | } 46 | 47 | return $pid; 48 | } 49 | 50 | 51 | /** 52 | * @inheritdoc 53 | */ 54 | public function isRunning(int $pid): bool 55 | { 56 | return false; 57 | } 58 | 59 | 60 | /** 61 | * Wait for the a thread started via call() to end. 62 | * 63 | * @param int $pid The pid to wait for 64 | * 65 | * @return int The exit code of the thread 66 | */ 67 | public function wait(int $pid): int 68 | { 69 | return $this->status[$pid]; 70 | } 71 | 72 | 73 | /** 74 | * Get any exceptions thrown by the threads. 75 | * 76 | * @return \Throwable[] 77 | */ 78 | public function getExceptions(): array 79 | { 80 | return $this->exceptions; 81 | } 82 | 83 | 84 | /** 85 | * Method to be called when the adapter is finished with. 86 | * 87 | * @return void 88 | */ 89 | public function cleanup() 90 | { 91 | $this->pid = 0; 92 | $this->exceptions = []; 93 | $this->status = []; 94 | } 95 | } 96 | -------------------------------------------------------------------------------- /src/Threads.php: -------------------------------------------------------------------------------- 1 | limit = $limit; 30 | 31 | if ($fork === null) { 32 | $fork = new Fork(); 33 | } 34 | $this->fork = $fork; 35 | } 36 | 37 | 38 | /** 39 | * @inheritdoc 40 | */ 41 | public function call(callable $func, ...$args): int 42 | { 43 | if (count($this->getPIDs()) >= $this->limit) { 44 | $this->waitForAnyThread(); 45 | } 46 | 47 | $pid = $this->fork->call($func, ...$args); 48 | 49 | return $pid; 50 | } 51 | 52 | 53 | /** 54 | * @inheritdoc 55 | */ 56 | public function isRunning(int $pid): bool 57 | { 58 | return $this->fork->isRunning($pid); 59 | } 60 | 61 | 62 | /** 63 | * @inheritdoc 64 | */ 65 | public function wait(int $pid = null): ForkInterface 66 | { 67 | $this->fork->wait($pid); 68 | return $this; 69 | } 70 | 71 | 72 | /** 73 | * @inheritdoc 74 | */ 75 | public function getPIDs(): array 76 | { 77 | return $this->fork->getPIDs(); 78 | } 79 | 80 | 81 | /** 82 | * If we've exhausted our limit of threads, wait for one to finish. 83 | * 84 | * @return void 85 | */ 86 | private function waitForAnyThread() 87 | { 88 | while (true) { 89 | foreach ($this->getPIDs() as $pid) { 90 | if (!$this->isRunning($pid)) { 91 | return; 92 | } 93 | } 94 | 95 | # If none of the threads have finished let, wait for a second before checking again 96 | sleep(1); 97 | } 98 | } 99 | } 100 | --------------------------------------------------------------------------------