c++


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 ?

Related Links

x86 MASM - passing and accessing a 2D array
Boost.spirit x3 compiler error when using semantic action in VS15
g++ undefined reference with a shared library [duplicate]
How can I pass an ifstream as argument to std::thread function?
File handling in c++ to read two integers
linux scheduling to strictly prefer higher priority thread than low priority thread
Returning reference using a ternery expression causes runtime error
In which cases is it okay to allocate on the stack
Simplest way to know a class's type
Draw a vector<glm::vec3> opengl c++
Normal member methods with same name as templated member methods
Efficiently converting complex to its polar form
A* Pathfinding without diagonal movement
Extending namespace std with backported types and templates from newer C++ standards
What is address 0xbaddc0dedeadbead “Bad decode dead bead”
General Solution for classes in which copy constructor using default constructor

Categories

HOME
.htaccess
github
momentjs
veins
angular-material2
informix
web-crawler
logistic-regression
keyboard-shortcuts
speech-recognition
axis2
mapkit
apache-spark-2.0
lokijs
log4net
corba
trackjs
jxmaps
android-constraintlayout
mitmproxy
cookie-session
angle
frama-c
rubinius
edi
ebcdic
angular-openlayers
week-number
pi4j
spacing
ipc
cad
asn.1
google-tv
scada
event-listeners
nsset
qnx
reduce
exports-loader
sp-executesql
opscenter
unicode-string
android-gson
schemaless
embedded-javascript
nslog
motorola
ldflags
code-collaborator
metamodel
kendo-datepicker
iis-8.5
django-class-based-views
wns
kdiff3
customdialog
sos
zend-studio
stage3d
frontpage
octopress
lg
cmfctoolbar
approximation
.a
topological-sort
orchardcms-1.6
irssi
jquery-dropkick
sequel
runscope
knockout-mapping-plugin
nsurlprotocol
countries
c++builder-6
uipicker
sniffing
batoo
opengl-es-1.1
array-formulas
jquery-textext
shadowbox
pubchem
wymeditor
sqa
assetslibrary
web-setup-project
fibonacci-heap
httpverbs
stack-unwinding
loose-coupling
duck-typing
jquery-ui-plugins
html-rendering
testing-strategies

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App