1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108
| class SafeFiberExecutor { public static function execute(callable $task, array $args = []): mixed { $fiber = new Fiber(function () use ($task, $args) { try { return call_user_func_array($task, $args); } catch (Throwable $e) { error_log("纤程执行错误: " . $e->getMessage()); return [ 'error' => true, 'message' => $e->getMessage(), 'code' => $e->getCode(), 'trace' => $e->getTraceAsString() ]; } }); try { return $fiber->start(); } catch (FiberError $e) { return [ 'error' => true, 'message' => '纤程执行失败: ' . $e->getMessage(), 'code' => $e->getCode() ]; } } public static function executeMultiple(array $tasks): array { $results = []; $fibers = []; foreach ($tasks as $index => $taskData) { $task = $taskData['task']; $args = $taskData['args'] ?? []; $fibers[$index] = new Fiber(function () use ($task, $args) { try { return [ 'success' => true, 'result' => call_user_func_array($task, $args) ]; } catch (Throwable $e) { return [ 'success' => false, 'error' => $e->getMessage(), 'code' => $e->getCode() ]; } }); } foreach ($fibers as $index => $fiber) { try { $results[$index] = $fiber->start(); } catch (FiberError $e) { $results[$index] = [ 'success' => false, 'error' => '纤程启动失败: ' . $e->getMessage() ]; } } return $results; } }
$tasks = [ [ 'task' => function ($x, $y) { if ($y === 0) { throw new DivisionByZeroError('除零错误'); } return $x / $y; }, 'args' => [10, 2] ], [ 'task' => function ($x, $y) { if ($y === 0) { throw new DivisionByZeroError('除零错误'); } return $x / $y; }, 'args' => [10, 0] ], [ 'task' => function ($str) { return strtoupper($str); }, 'args' => ['hello world'] ] ];
$results = SafeFiberExecutor::executeMultiple($tasks);
foreach ($results as $index => $result) { if ($result['success']) { echo "任务 $index 成功: {$result['result']}\n"; } else { echo "任务 $index 失败: {$result['error']}\n"; } }
|