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

Debugging CUDA - CudaUnknownError
Simple decoding program C++ [closed]
Qt Application Slowing Down
How to Set a Class Instance Name to a Variable (C++)
DirectX 11 Make a square.
DeleteTimerQueueTimer() access violation and/or deadlock [closed]
Can the number of parameters determined by templates in c++?
Handling hotkeys with modifiers
HippoMocks With weak_ptr
How to validate JSON Schema in Objective-C?
C++ Have two child classes share a variable from their base class
is it safe to calling a member function not defined on the base class from of a derived class in c++?
Microsoft C exception: std::bad_alloc at memory location 0x0017F5E0
How to parallellize an outer loop with openMP with serial inner loop for array addition
C++ Get HTML Source
Stack will only display first value?

Categories

HOME
menu
qt5
payment
less
dependent-type
userform
caffe
webserver
chapel
ieee-754
spark-dataframe
widget
datepicker
relation
ninja
corba
salt-stack
photon
jlabel
firebreath
sirikit
.net-4.5
pfsense
angle
android-appbarlayout
heatmap
jqassistant
choropleth
inorder
android-adapter
package-name
javapoet
legacy
polymer-serve
tail-recursion
azure-virtual-machine
rrd4j
redhat-bpm
predict
grayscale
retrieve-and-rank
cartography
terminal-emulator
schemaless
kubernetes-health-check
mongodb-scala
ember-cli-mirage
playstation
synopsys-vcs
greenlets
jquery-tags-input
machinekey
azure-webjobssdk
helium
metamodel
strstream
correspondence-analysis
grape
stl-format
phpinfo
ibm-jazz
blackberry-simulator
mpld3
webots
fody-propertychanged
html5builder
fileapi
angularjs-ng-options
excel-2008
gstat
akeneo
jison
mashape
kiosk-mode
zenoss
sql-job
sqloledb
knockout-mapping-plugin
dav
firstdata
iron
apiaxle
stockquotes
dynamic-html
fubumvc
firepad
jquery-textext
icefaces-1.8
fatwire
springmockito
ctime
sts-securitytokenservice
scopes
scalaquery
umbraco5
pasteboard
silverlight-embedded
cocos2d-python
www-mechanize
executequery
open-basedir
abbreviation

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