简体   繁体   English

如何创建多线程清洁器?

[英]How can i create multiple threads cleaner?

so i creating multiple threads with the following way:所以我用以下方式创建多个线程:

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

I doing that around 10 times, and it works perfectly fine, but it just looks ugly, is there any method to do it cleaner?我这样做了大约 10 次,它工作得很好,但它看起来很丑,有什么方法可以让它更干净吗? Thanks!谢谢!

You can achieve this syntax你可以实现这个语法

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

with this example :用这个例子:

#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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM