Threads in a vector can't be joined - c++

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.

Related

“Program received signal SIGABRT, Aborted.“error in remote Linux,why? [duplicate]

I created and executed a simple thread on my system. when I execute this program, I have the error message : Enable multithreading to use std::thread: Operation not permitted
some details about my system :
linux ubuntu 13.10
g++ 4.8.1
I compile the source code including the library pthread
The source code:
#include <iostream>
#include <thread>
using namespace std;
void func(void) {
cout << "test thread" << endl;
}
int main() {
cout << "start" << endl;
thread t1 (func);
t1.join();
cout << "end" << endl;
return 0;
}
It seems that you are trying to use C++11 threads. If it is true, then
correct #include <thread> and #include <iostream>, i.e. do not use " in these lines and add # in front of them.
compile with g++ -std=c++11 q.cpp -lpthread (dependency order matters for newer g++)
Hint: when you are using threads in a static linked library and use this library in an executable, then you have to add the flag -pthread to the link command for the executable. Example:
g++ Obj1.o Obj2.o MyStaticLib.a -o MyExecutable -pthread

Thread doesn't work with an error: Enable multithreading to use std::thread: Operation not permitted

I created and executed a simple thread on my system. when I execute this program, I have the error message : Enable multithreading to use std::thread: Operation not permitted
some details about my system :
linux ubuntu 13.10
g++ 4.8.1
I compile the source code including the library pthread
The source code:
#include <iostream>
#include <thread>
using namespace std;
void func(void) {
cout << "test thread" << endl;
}
int main() {
cout << "start" << endl;
thread t1 (func);
t1.join();
cout << "end" << endl;
return 0;
}
It seems that you are trying to use C++11 threads. If it is true, then
correct #include <thread> and #include <iostream>, i.e. do not use " in these lines and add # in front of them.
compile with g++ -std=c++11 q.cpp -lpthread (dependency order matters for newer g++)
Hint: when you are using threads in a static linked library and use this library in an executable, then you have to add the flag -pthread to the link command for the executable. Example:
g++ Obj1.o Obj2.o MyStaticLib.a -o MyExecutable -pthread

Spurious wakeups on condition_variable with g++ and clang++

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.

Why is this cppreference demo program causing a segmentation fault?

I'm reviewing a variant of the std::move function by testing it on my compiler. For some reason this program fails in both latest clang++ and g++4.8. In my opinion this looks like a correct program that should work.
g++-4.8 -std=c++1y -O3 -Wall -pthread main.cpp && ./a.out
terminate called without an active exception
/tmp/1370796977-600590525/cmd.sh: line 7: 22819 Aborted (core dumped) ./a.out
#include <iostream>
#include <vector>
#include <list>
#include <iterator>
#include <thread>
#include <chrono>
void f(int n)
{
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "thread " << n << " ended" << '\n';
}
int main()
{
std::vector<std::thread> v;
v.emplace_back(f, 1);
v.emplace_back(f, 2);
v.emplace_back(f, 3);
std::list<std::thread> l;
for(auto& t : l) t.join();
}
I notice that the part that causes the error is the emplace_back lines. When I remove them the program compiles normally. Why is this happening and why is it failing on all compilers I've tried thus far?
You are not joining the threads in main(). You need
for(auto& t : v) t.join();
// ^ Look, v not l
Alternatively, place this line before your original loop to move the threads from the v into l:
std::move(v.begin(), v.end(), std::back_inserter(l));
for(auto& t : l) t.join();
you try iterate over empty l, but 'join is not accomplished for real threads
You seem to leave the list empty, and exit main with unjoined threads in v.
IIRC destructor of std::thread calls terminate if not joined.

C++ terminate called without an active exception

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