【问题标题】:How can i create multiple threads cleaner?如何创建多线程清洁器?
【发布时间】:2021-12-04 22:22:23
【问题描述】:

所以我用以下方式创建多个线程:

    std::thread Thread1(func1); Thread1.detach();
    std::thread Thread2(func2); Thread2.detach();

我这样做了大约 10 次,效果很好,但是 它看起来很丑,有什么方法可以让它更干净吗?谢谢!

【问题讨论】:

  • 只做一个循环?
  • 您不需要为每个线程变量命名。 std::thread(func1).detach(); 也可以。我这么干净吗?
  • @IgorTandetnik 是的,我知道这一点。但我更多地谈论的是减少线路
  • for (auto f : {func1, func2}) std::thread(f).detach();
  • detach() 通常是一个错误。它使您无法控制和尴尬的同步问题。

标签: c++ multithreading


【解决方案1】:

你可以实现这个语法

for (auto func : { func1, func2 }) async(func);

这个例子:

#include <chrono>
#include <functional>
#include <vector>
#include <thread>
#include <iostream>

void func1()
{
    std::cout << "1";
}

void func2()
{
    std::cout << "2";
}

// Make functions out of repeated things 
template<typename Fn>
void async(Fn fn)
{
    std::thread(fn).detach();
}

int main()
{
    for (auto func : { func1, func2 }) async(func);

    // I really don't like sleeps.
    // but async doesn't allow for any kind of synchronization
    // so allow for some time to pass so functions can show output
    std::this_thread::sleep_for(std::chrono::seconds(2));

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-26
    • 2015-12-03
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多