-- Copyright (c) 2026 Huawei Technologies Co., Ltd.
-- openUBMC is licensed under Mulan PSL v2.
-- You can use this software according to the terms and conditions of the Mulan PSL v2.
-- You may obtain a copy of Mulan PSL v2 at: http://license.coscl.org.cn/MulanPSL2
-- THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
-- EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
-- MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
-- See the Mulan PSL v2 for more details.

local class = require 'mc.class'
local skynet = require 'skynet'

-- 并行任务处理
local Actuator = class()
function Actuator:ctor(init_completed_code, catch_completed_code)
    self.task_count = 0
    self.completed_code = init_completed_code
    self.catch_completed_code = catch_completed_code
    self.co = coroutine.running()
end

-- 创建并行任务
function Actuator:concurrent_run(cb)
    self.task_count = self.task_count + 1
    skynet.fork(function ()
        local res = cb()
        if res == self.catch_completed_code then
            self.completed_code = self.catch_completed_code
        end
        self.task_count = self.task_count - 1
        if self.task_count == 0 then
            skynet.wakeup(self.co)
        end
    end)
end

function Actuator:waitting()
    if self.task_count ~= 0 then
        skynet.wait(self.co)
    end
end

function Actuator:get_completed_code()
    return self.completed_code
end

return Actuator