在函数中使用传递的参数列表

Using passed argument list in a function

我正在尝试用 C++ 构建一个线程管理器系统,我向它发出命令,如果有可用的线程,它就会开始工作。我制作了一个模板,因为我不假设函数应该如何传递给系统,并且因为我希望它在一般函数上工作。

整个概念对我来说都是理论上的。我的想法是:

所以我可以跟踪正在使用的线程数。

template <typename _Ty> void ThreadManager::Run(_Ty T, ...) //T should be a function
{
    using namespace std::literals::chrono_literals;
    while (!is_free_thread_available())std::this_thread::sleep_for(1ms);

    va_list args;
    va_start(args, T);

    auto F = void[=]() {
        std::this_thread::sleep_for(1ms); //to make sure the thread will be added to the vector
        T(args); //i assume this should not work
        for (int i = 0; i < Threads.size(); i++)     //Threads = std::vector<std::thread>
            auto& t = Threads[i];
            if (std::this_thread::get_id() == t.get_id())
            {
                Threads.erase(Threads.begin() + i); t.detach(),  break; //not sure if detaching the active thread works
            }
    }

    std::thread Thread(F);
    Threads.push_back(Thread);

}

此代码没有 运行。它 returns 一个未解析的外部符号。我可能需要一些帮助来制作它 运行

当您使用 C++ 时,请避免 C-ellipsis 并使用可变参数模板:

这将解决您的编译问题:

template <typename Func, typename ... Args>
void ThreadManager::Run(Func func, Args... args)
{
    using namespace std::literals::chrono_literals;

    while (!is_free_thread_available()) std::this_thread::sleep_for(1ms);

    auto F = void[=]() {
        func(args...);

        // TODO: Synchronization needed to avoid race condition
        for (int i = 0; i < Threads.size(); i++)     //Threads = std::vector<std::thread>
            auto& t = Threads[i];
            if (std::this_thread::get_id() == t.get_id())
            {
                Threads.erase(Threads.begin() + i);
                break;
            }
    }
    // TODO: Synchronization needed to avoid race condition
    Threads.emplace_back(F);
}

请注意,您还必须解决同步问题