簡體   English   中英

如何創建多線程清潔器?

[英]How can i create multiple threads cleaner?

所以我用以下方式創建多個線程:

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

我這樣做了大約 10 次,它工作得很好,但它看起來很丑,有什么方法可以讓它更干凈嗎? 謝謝!

你可以實現這個語法

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM