Take the following code:
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
using namespace std;
int main() {
mutex m;
condition_variable c;
bool fired = false;
int i = 0;
// This thread counts the times the condition_variable woke up.
// If no spurious wakeups occur it should be close to 5.
thread t([&]() {
unique_lock<mutex> l(m);
while (!fired) {
c.wait_for(l, chrono::milliseconds(100));
++i;
}
});
// Here we wait for 500ms, then signal the other thread to stop
this_thread::sleep_for(chrono::milliseconds(500));
{
unique_lock<mutex> l(m);
fired = true;
c.notify_all();
cout << i << endl;
}
t.join();
}
Now, when I build this using clang++ -std=c++11 -pthread foo.cpp everything is fine, it outputs 4 on my machine. When I build it with g++ -std=c++11 -pthread foo.cpp however I get something very large every time, e.g. 81513. I realize the number of spurious wakeups is undefined, but I was surprised to see it so high.
Additional information: When I replace the wait_for by a simple wait both clang and g++ output 0.
Is this a bug / feature in g++? Why is it even different from clang? Can I get it to behave more reasonably?
Also: gcc version 4.7.3 (Debian 4.7.3-4).
I managed to get g++-4.8 running, and the problem is gone. Very weird, seems like a bug in g++-4.7.3, although I wasn't able to reproduce it on another machine.
Related
// main.cpp
#include <iostream>
#include <chrono>
#include <condition_variable>
#include <mutex>
#include <thread>
int main(int nArgCnt, char*ppArgs[]) {
using namespace std::chrono_literals;
std::mutex mtx;
std::unique_lock<decltype(mtx)> lock(mtx);
std::condition_variable condVar;
int x = 0;
condVar.wait(lock, [&] {
std::this_thread::sleep_for(1ms);
std::cout << x << std::endl;
return x > 0;
});
}
I build above code with g++ main.cpp -o test, the the test prints infinite lines:
0
0
0
0
...
However, if I built with g++ main.cpp -lpthread -o test, only one line is printed:
0
I have tested with different versions of Linux and different versions of g++ compilers, and got the same phenomenon.
Why adding -lpthread or not lead to different behavior of the code?
Ps. If I removed the line std::this_thread::sleep_for(1ms); , the test always print infinite lines whether -lpthread is added or not. So weird...
Test environment: Ubuntu 18.04.3 LTS g++ (Ubuntu 7.5.0-3ubuntu1~18.04) 7.5.0.
Can std::mutex be reentrant? Why does the following test code 1 pass?
code1:
#include <iostream>
#include <mutex>
std::mutex g_mtx4val;
int g_val = 5;
void test() {
std::lock_guard<std::mutex> lck(g_mtx4val);
std::cout << "g_val=" << g_val << std::endl;
if (g_val > 0) {
--g_val;
test();
}
}
int main() {
test();
std::cout << "done ...." << std::endl;
return 0;
}
peanut#peanut:~/demo$ g++ test.cpp
peanut#peanut:~/demo$ ./a.out
g_val=5
g_val=4
g_val=3
g_val=2
g_val=1
g_val=0
done ...
code2:
// Same code 1
int main() {
std::thread t1(test);
t1.join();
std::cout << "done ...." << std::endl;
return 0;
}
peanut#peanut:~/demo$ g++ test2.cpp -lpthread
peanut#peanut:~/demo$ ./a.out
g_val=5
^C
peanut#peanut:~/demo$
code2 has a deadlock.
Why code1 can pass the test?
From the documentation page:
mutex offers exclusive, non-recursive ownership semantics
So the answer to the question in the title is no.
Can std::mutex be reentrant?
No, but if you want a recursive mutex, the std::recursive_mutex class provides that functionality.
Why does the following test code 1 pass?
What behavior were you expecting to see? The std::mutex documentation page simply says:
A calling thread must not own the mutex prior to calling lock or try_lock.
... it doesn't say what will happen if the calling thread breaks the above rule; which means that a program that breaks the rule may "appear to work", but even so is still incorrect and buggy.
I want to store a collection of threads in a vector, and join them all before exiting my program. I receive the following error when trying to join the first thread no matter how many I place in the collection:
system_error: thread::join failed: No such process
Here is some simple code that demonstrates my issue:
#include <thread>
#include <iostream>
#include <vector>
#include <functional>
using std::cout;
using std::endl;
using std::vector;
using std::thread;
using std::mem_fn;
int main()
{
vector<thread> threads(1);
threads.push_back(thread([]{ cout << "Hello" << endl; }));
for_each(threads.begin(), threads.end(), mem_fn(&thread::join));
// also tried --> for(thread &t : threads) t.join()
}
And I'm building it using the following (tried clang++ 4.2.1 and g++ 5.3.1):
g++ -o src/thread_test.o -c -std=c++14 src/thread_test.cpp -pthread
g++ -o thread_test src/thread_test.o -pthread
I see lots of examples doing just this around the internet. Did something change in the contract of <thread> or <vector> that's rendered these examples defunct?
NOTE: As an aside for future readers, I ended up adding the (1) constructor argument after trying {} assignment, which fails due to a private copy constructor. In trying to avoid the copy constructor I ended up allocating uninitialized threads -- careless mistake.
vector<thread> threads(1);
This creates a thread which can be accessed at index 0.
threads.push_back(thread([]{ cout << "Hello" << endl; }));
This adds a second thread which can be accessed at index 1.
for_each(threads.begin(), threads.end(), mem_fn(&thread::join));
This is going to call join on both thread objects. However, the first one was never started therefore it is not joinable.
Instead, you could replace vector<thread> threads(1); with vector<thread> threads; threads.reserve(1); and keep using push_back.
I am getting a C++ error with threading:
terminate called without an active exception
Aborted
Here is the code:
#include <queue>
#include <thread>
#include <mutex>
#include <condition_variable>
template<typename TYPE>
class blocking_stream
{
public:
blocking_stream(size_t max_buffer_size_)
: max_buffer_size(max_buffer_size_)
{
}
//PUSH data into the buffer
blocking_stream &operator<<(TYPE &other)
{
std::unique_lock<std::mutex> mtx_lock(mtx);
while(buffer.size()>=max_buffer_size)
stop_if_full.wait(mtx_lock);
buffer.push(std::move(other));
mtx_lock.unlock();
stop_if_empty.notify_one();
return *this;
}
//POP data out of the buffer
blocking_stream &operator>>(TYPE &other)
{
std::unique_lock<std::mutex> mtx_lock(mtx);
while(buffer.empty())
stop_if_empty.wait(mtx_lock);
other.swap(buffer.front());
buffer.pop();
mtx_lock.unlock();
stop_if_full.notify_one();
return *this;
}
private:
size_t max_buffer_size;
std::queue<TYPE> buffer;
std::mutex mtx;
std::condition_variable stop_if_empty,
stop_if_full;
bool eof;
};
I modeled my code around this example:
http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html
What am I doing wrong and how do I fix the error?
When a thread object goes out of scope and it is in joinable state, the program is terminated. The Standard Committee had two other options for the destructor of a joinable thread. It could quietly join -- but join might never return if the thread is stuck. Or it could detach the thread (a detached thread is not joinable). However, detached threads are very tricky, since they might survive till the end of the program and mess up the release of resources. So if you don't want to terminate your program, make sure you join (or detach) every thread.
How to reproduce that error:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
cout << "task1 says: " << msg;
}
int main() {
std::thread t1(task1, "hello");
return 0;
}
Compile and run:
el#defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el#defiant ~/foo4/39_threading $ ./s
terminate called without an active exception
Aborted (core dumped)
You get that error because you didn't join or detach your thread.
One way to fix it, join the thread like this:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <thread>
using namespace std;
void task1(std::string msg){
cout << "task1 says: " << msg;
}
int main() {
std::thread t1(task1, "hello");
t1.join();
return 0;
}
Then compile and run:
el#defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el#defiant ~/foo4/39_threading $ ./s
task1 says: hello
The other way to fix it, detach it like this:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
cout << "task1 says: " << msg;
}
int main()
{
{
std::thread t1(task1, "hello");
t1.detach();
} //thread handle is destroyed here, as goes out of scope!
usleep(1000000); //wait so that hello can be printed.
}
Compile and run:
el#defiant ~/foo4/39_threading $ g++ -o s s.cpp -pthread -std=c++11
el#defiant ~/foo4/39_threading $ ./s
task1 says: hello
Read up on detaching C++ threads and joining C++ threads.
Eric Leschinski and Bartosz Milewski have given the answer already. Here, I will try to present it in a more beginner friendly manner.
Once a thread has been started within a scope (which itself is running on a thread), one must explicitly ensure one of the following happens before the thread goes out of scope:
The runtime exits the scope, only after that thread finishes executing. This is achieved by joining with that thread. Note the language, it is the outer scope that joins with that thread.
The runtime leaves the thread to run on its own. So, the program will exit the scope, whether this thread finished executing or not. This thread executes and exits by itself. This is achieved by detaching the thread. This could lead to issues, for example, if the thread refers to variables in that outer scope.
Note, by the time the thread is joined with or detached, it may have well finished executing. Still either of the two operations must be performed explicitly.
First you define a thread. And if you never call join() or detach() before calling the thread destructor, the program will abort.
As follows, calling a thread destructor without first calling join (to wait for it to finish) or detach is guarenteed to immediately call std::terminate and end the program.
Either implicitly detaching or joining a joinable() thread in its
destructor could result in difficult to debug correctness (for detach)
or performance (for join) bugs encountered only when an exception is
raised. Thus the programmer must ensure that the destructor is never
executed while the thread is still joinable.
As long as your program die, then without detach or join of the thread, this error will occur. Without detaching and joining the thread, you should give endless loop after creating thread.
int main(){
std::thread t(thread,1);
while(1){}
//t.detach();
return 0;}
It is also interesting that, after sleeping or looping, thread can be detach or join. Also with this way you do not get this error.
Below example also shows that, third thread can not done his job before main die. But this error can not happen also, as long as you detach somewhere in the code.
Third thread sleep for 8 seconds but main will die in 5 seconds.
void thread(int n) {std::this_thread::sleep_for (std::chrono::seconds(n));}
int main() {
std::cout << "Start main\n";
std::thread t(thread,1);
std::thread t2(thread,3);
std::thread t3(thread,8);
sleep(5);
t.detach();
t2.detach();
t3.detach();
return 0;}
yes, the thread must be join(). when the main exit
Tried the following example compiled with g++ -std=gnu++0x t1.cpp and g++ -std=c++0x t1.cpp but both of these result in the example aborting.
$ ./a.out
terminate called after throwing an instance of 'std::system_error'
what():
Aborted
Here is the sample:
#include <thread>
#include <iostream>
void doSomeWork( void )
{
std::cout << "hello from thread..." << std::endl;
return;
}
int main( int argc, char *argv[] )
{
std::thread t( doSomeWork );
t.join();
return 0;
}
I'm trying this on Ubuntu 11.04:
$ g++ --version
g++ (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
Anyone knows what I've missed?
You have to join std::threads, just like you have to join pthreads.
int main( int argc, char *argv[] )
{
std::thread t( doSomeWork );
t.join();
return 0;
}
UPDATE: This Debian bug report pointed me to the solution: add -pthread to your commandline. This is most probably a workaround until the std::thread code stabilizes and g++ pulls that library in when it should (or always, for C++).
Please use the pthread library during the compilation: g++ -lpthread.
Simplest code to reproduce that error and how to fix:
Put this in a file called s.cpp:
#include <iostream>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <thread>
using namespace std;
void task1(std::string msg){
cout << "task1 says: " << msg;
}
int main(){
std::thread t1(task1, "hello");
usleep(1000000);
t1.detach();
}
Compile like this:
el#apollo:~/foo7$ g++ -o s s.cpp -std=c++0x
Run it like this, the error happens:
el#apollo:~/foo7$ ./s
terminate called after throwing an instance of 'std::system_error'
what(): Operation not permitted
Aborted (core dumped)
To fix it, compile it like this with the -pthread flag:
g++ -o s s.cpp -std=c++0x -pthread
./s
Then it works correctly:
task1 says: hello
For what it's worth, I had different issue with similar code using threads in g++ (MinGW). Work-around was to put some "delay" between creating a thread and joining it.
Code with infrequently failing assertion:
std::atomic_bool flag{false};
std::thread worker( [&] () { flag.store(true); } );
worker.join();
assert(flag.load()); // Sometimes fails
Work-around:
std::atomic_bool flag{false};
std::thread worker( [&] () { flag.store(true); } );
while (not flag.load()) { std::this_thread::yield(); }
worker.join();
assert(flag.load()); // Works fine
Note that yield() alone did not help, hence the while loop. Using sleep_for(...) also works.
You need to link to run time library