简体   繁体   中英

How to find out if other threads are running?

I have a "watch thread" which checks whether other threads are running and calculates some data. If these threads end I want to finish my watch thread, too. How can I do it?

#include <iostream>
#include <thread>

using namespace std;

void f1() {
    cout << "thread t1" << endl;
    for (int i=0; i<1000; ++i) {
       cout << "t1: " << i << endl;
    }   
}

void f2() {
    cout << "thread t2" << endl;
    while (T1_IS_RUNNING) {
       cout << "t1 still running" << endl;
    }   
}

int main() {
    thread t1(f1);
    thread t2(f2);

    t1.join();
    t2.join();

    return 0;
}

In the example above I need to implement T1_IS_RUNNING . Any ideas how to do it? My guess is to get number of running threads but I haven't found any related method in STL.

There is a How to check if a std::thread is still running? already, but I think they use too complicated solutions for my case. Isn't a simple thread counter (std::atomic) good enough?

You can just use a flag for it ( running example ):

#include <iostream>
#include <thread>

using namespace std;

bool T1_IS_RUNNING = true;
void f1() {
    cout << "thread t1" << endl;
    for (int i=0; i<1000; ++i) {
       cout << "t1: " << i << endl;
    }
    T1_IS_RUNNING = false;
    cout << "thread t1 finish" << endl;
}

void f2() {
    cout << "thread t2" << endl;
    while (T1_IS_RUNNING) {
       cout << "t1 still running" << endl;
    }   
    cout << "thread t2 finish" << endl;
}

int main() {
    thread t1(f1);
    thread t2(f2);

    t1.join();
    t2.join();

    return 0;
}

This is safe as long as only one of them writes the flag and the other reads it, otherwise you need to use an atomic flag, a mutex or a semaphore.

With atomic_int:

int main(){
    std::atomic_int poor_man_semaphore{0};
    poor_man_semaphore++;
    std::thread t1([&]()
    {
        std::this_thread::sleep_for(std::chrono::seconds(100));
        poor_man_semaphore--;
    });
    poor_man_semaphore++;
    std::thread t2([&]()
    {
         std::this_thread::sleep_for(std::chrono::seconds(1));
         poor_man_semaphore--;
    });
    poor_man_semaphore++;
    std::thread t3([&]()
    {
         std::this_thread::sleep_for(std::chrono::seconds(1));
         poor_man_semaphore--;
    });

    t2.join();
    t3.join();
    while ( poor_man_semaphore > 0 )
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));

    }
    t1.join();
    return 0;
}

Let me give a quick fix to the code, as there is already a detailed post , this will not be long.

This answer exists because there are many wrong answers here.

My interpretation of your problem is you want a "watch thread" to do work while other threads are still alive, but stop whenever others stop.

#include <fstream>
#include <thread>
#include <atomic>  // this is REQUIRED, NOT OPTIONAL

using namespace std;

atomic_int count(1);  // REQUIRED to be atomic

void f1() {
    ofstream f1out{"f1out.txt"};
    f1out << "thread t1" << endl;
    for (int i=0; i<1000; ++i) {
       f1out << "t1: " << i << endl;
    }
    count--;
}

void f2() {
    ofstream f2out{"f2out.txt"};
    f2out << "thread t2" << endl;
    while (count > 0) {
       f2out << "t1 still running" << endl;
    }
}

int main() {
    thread t1(f1);
    thread t2(f2);

    t1.join();
    t2.join();
}

Notes on atomic

The syntax of atomic_int might look like an int but they are different and failing to use atomic_int is undefined behaviour .

From [intro.races] , emphasis mine

Two expression evaluations conflict if one of them modifies a memory location and the other one reads or modifies the same memory location. [...]

The execution of a program contains a data race if it contains two potentially concurrent conflicting actions, at least one of which is not atomic, and neither happens before the other [...] . Any such data race results in undefined behavior .

Notes on cout

Likewise, it is a data race if the threads use cout concurrently , I can't find a simple replacement to preserve the meaning and effect. I opt into using ofstream in the end.

For people concerned

Yes, the atomic operations need not be sequentially consistent but that really doesn't help with clarity.

This link might help you. Amongst a lot of solutions, one seems quite easy to implement :

An easy solution is to have a boolean variable that the thread sets to true on regular intervals, and that is checked and set to false by the thread wanting to know the status. If the variable is false for to long then the thread is no longer considered active.
A more thread-safe way is to have a counter that is increased by the child thread, and the main thread compares the counter to a stored value and if the same after too long time then the child thread is considered not active.

May be you could set an array of boolean, one by thread you run, and then check it whenever you want to know if other threads are running ?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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