Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reporting a thread progress to main thread in C++

In C/C++ How can I make the threads(POSIX pthreads/Windows threads) to give me a safe method to pass progress back to the main thread on the progress of the execution or my work that I’ve decided to perform with the thread.

Is it possible to report the progress in terms of percentage ?

like image 580
Laavaa Avatar asked Dec 26 '22 15:12

Laavaa


1 Answers

I'm going to assume a very simple case of a main thread, and one function. What I'd recommend is passing in a pointer to an atomic (as suggested by Kirill above) for each time you launch the thread. Assuming C++11 here.

using namespace std;

void threadedFunction(atomic<int>* progress)
{
    for(int i = 0; i < 100; i++)
    {
        progress->store(i);  // updates the variable safely
        chrono::milliseconds dura( 2000 );
        this_thread::sleep_for(dura); // Sleeps for a bit
    }
    return;
}

int main(int argc, char** argv)
{
    // Make and launch 10 threads
    vector<atomic<int>> atomics;
    vector<thread> threads;
    for(int i = 0; i < 10; i++)
    {
        atomics.emplace_back(0);
        threads.emplace_back(threadedFunction, &atomics[i]);
    }

    // Monitor the threads down here
    // use atomics[n].load() to get the value from the atomics
    return 0;
}

I think that'll do what you want. I omitted polling the threads, but you get the idea. I'm passing in an object that both the main thread and the child thread know about (in this case the atomic<int> variable) that they both can update and/or poll for results. If you're not on a full C++11 thread/atomic support compiler, use whatever your platform determines, but there's always a way to pass a variable (at the least a void*) into the thread function. And that's how you get something to pass information back and forth via non-statics.

like image 179
Kevin Anderson Avatar answered Jan 09 '23 18:01

Kevin Anderson