C ++ 11 - Workflow Management

I am new to threading in C ++ 11, and I am wondering how to manage workflows (using the standard library) to perform some kind of task, and then die. I have a thread pool vector<thread *> thread_poolthat maintains a list of active threads.

Let's say I start a new thread and add it to the pool with thread_pool.push_back(new thread(worker_task)), where it worker_taskis defined as follows:

void worker_task()
{
    this_thread::sleep_for(chrono::milliseconds(1000));
    cout << "Hello, world!\n"
}

Once the workflow is complete, what is the best way to reliably remove the thread from the pool? The main thread must work continuously and cannot be blocked during a call join. The general structure of the code confuses me more than the subtleties of synchronization.

Edit: Looks like I misused the concept of a pool in my code. All I had in mind was that I have a list of threads that currently work.

+4
source share
1 answer

You can use std :: thread :: detash to "separate the thread of execution from the thread object so that execution continues independently. Any allocated resources will be freed after the thread exits."

If each thread must show its state, you can move this functionality to a stream function.

std::mutex mutex;
using strings = std::list<std::string>;
strings info;

strings::iterator insert(std::string value) {
    std::unique_lock<std::mutex> lock{mutex};
    return info.insert(info.end(), std::move(value));
}

auto erase(strings::iterator p) {
    std::unique_lock<std::mutex> lock{mutex};
    info.erase(p);
}

template <typename F>
void async(F f) {
    std::thread{[f] {
        auto p = insert("...");
        try {
            f();
        } catch (...) {
            erase(p);
            throw;
        }
        erase(p);
    }}.detach();
}
+3
source

Source: https://habr.com/ru/post/1546732/


All Articles