You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

线程间传递函数并获取返回值的实现方案咨询

工作线程请求主线程执行函数并同步获取返回值的实现验证

问题场景

假设我有一个工作线程执行如下逻辑代码:

Call1(); //executes on worker thread
Call2(); //executes on worker thread
Call3(); //executes on worker thread
ret = CallThatMustExecuteOnMainThread(arg1, arg2, argN);

正如函数名所示,CallThatMustExecuteOnMainThread及其参数需要在主线程中执行,返回值需赋值给ret。在该函数执行期间,工作线程需暂停执行,待其完成后再继续。说明:该函数会调用某外部动态库函数,且仅有一个工作线程执行上述调用。

主线程执行如下循环逻辑:

for (;;) {
  if (hasTaskFromWorkerThread)
    ExecuteTaskFromWorkerThread();
  else
    SomethingElse();
}

我无法确定应使用何种同步与数据传输机制来实现上述需求。

补充:概念验证实现

以下是我编写的一个概念验证实现:

#include <iostream>
#include <string>
#include <chrono>
#include <thread>
#include <future>
#include <mutex>
#include <condition_variable>
#include <functional>
#include <optional>
#include <conio.h>

std::mutex m;
std::condition_variable cv;

std::function<int()> onMainFunc;
using ResultType = decltype(onMainFunc)::result_type;
std::optional<ResultType> result;


const std::thread::id MAIN_THREAD_ID = std::this_thread::get_id();

static int ExecOnMainImpl(int x, int y) {
    return x + y;
}

struct S {
    static int ExecOnMain(int x, int y) {
        if (std::this_thread::get_id() == MAIN_THREAD_ID)
            return ExecOnMainImpl(x, y);
        else {
            {
                std::lock_guard<decltype(m)> lk(m);
                result.reset();
                onMainFunc = [x, y]() -> int { return ExecOnMainImpl(x, y); };
            }
            cv.notify_one();
            {
                std::unique_lock lk(m);
                cv.wait(lk, [] { return result.has_value(); });
                return result.value();
            }
        }
    }
};

void worker_thread() {
    using namespace std::chrono_literals;
    for (;;) {
        std::this_thread::sleep_for(5000ms);
        std::cout << S::ExecOnMain(1, 2) << "\n";
    }
}

int main()
{
    using namespace std::chrono_literals;

    auto future = std::async(std::launch::async, worker_thread);

    for (;;) {
        {
            std::unique_lock lk(m);
            if (cv.wait_for(lk, 500ms, [] { return onMainFunc != nullptr; })) {
                result = onMainFunc();
                onMainFunc = nullptr;
                lk.unlock();
                cv.notify_one();
            }
            else
                std::cout << "Doing something else" << "\n";
        }
    }

    future.get();
    
    return 0;
}

程序输出如下:

Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
3
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
Doing something else
3
Doing something else
Doing something else
......

提问

请问该实现是否合理?欢迎提供任何改进建议。


内容的提问来源于stack exchange,提问作者lhog

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.22 12:39:25