Home > Net >  How can i create multiple threads cleaner?
How can i create multiple threads cleaner?

Time:10-18

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? Thanks!

CodePudding user response:

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