PocketMine-MP 5.23.3 git-f7687af337d001ddbcc47b8e773f014a33faa662
Loading...
Searching...
No Matches
ThreadManager.php
1<?php
2
3/*
4 *
5 * ____ _ _ __ __ _ __ __ ____
6 * | _ \ ___ ___| | _____| |_| \/ (_)_ __ ___ | \/ | _ \
7 * | |_) / _ \ / __| |/ / _ \ __| |\/| | | '_ \ / _ \_____| |\/| | |_) |
8 * | __/ (_) | (__| < __/ |_| | | | | | | | __/_____| | | | __/
9 * |_| \___/ \___|_|\_\___|\__|_| |_|_|_| |_|\___| |_| |_|_|
10 *
11 * This program is free software: you can redistribute it and/or modify
12 * it under the terms of the GNU Lesser General Public License as published by
13 * the Free Software Foundation, either version 3 of the License, or
14 * (at your option) any later version.
15 *
16 * @author PocketMine Team
17 * @link http://www.pocketmine.net/
18 *
19 *
20 */
21
22declare(strict_types=1);
23
24namespace pocketmine\thread;
25
26use pmmp\thread\ThreadSafe;
27use pmmp\thread\ThreadSafeArray;
28use function spl_object_id;
29
30class ThreadManager extends ThreadSafe{
31
32 private static ?self $instance = null;
33
34 public static function init() : void{
35 self::$instance = new ThreadManager();
36 }
37
38 public static function getInstance() : ThreadManager{
39 if(self::$instance === null){
40 self::$instance = new ThreadManager();
41 }
42 return self::$instance;
43 }
44
46 private ThreadSafeArray $threads;
47
48 private function __construct(){
49 $this->threads = new ThreadSafeArray();
50 }
51
52 public function add(Worker|Thread $thread) : void{
53 $this->threads[spl_object_id($thread)] = $thread;
54 }
55
56 public function remove(Worker|Thread $thread) : void{
57 unset($this->threads[spl_object_id($thread)]);
58 }
59
63 public function getAll() : array{
64 $array = [];
68 foreach($this->threads as $key => $thread){
69 $array[$key] = $thread;
70 }
71
72 return $array;
73 }
74
75 public function stopAll() : int{
76 $logger = \GlobalLogger::get();
77
78 $erroredThreads = 0;
79
80 foreach($this->getAll() as $thread){
81 $logger->debug("Stopping " . $thread->getThreadName() . " thread");
82 try{
83 $thread->quit();
84 $logger->debug($thread->getThreadName() . " thread stopped successfully.");
85 }catch(ThreadException $e){
86 ++$erroredThreads;
87 $logger->debug("Could not stop " . $thread->getThreadName() . " thread: " . $e->getMessage());
88 }
89 }
90
91 return $erroredThreads;
92 }
93}