C++11 thread crash when access boost::asio::ip::tcp::socket - multithreading

I found that accessing tcp::socket from a std::thread will cause program terminated.
Here's the sample program from boost.
http://www.boost.org/doc/libs/1_53_0/doc/html/boost_asio/example/echo/blocking_tcp_echo_server.cpp
Compile it: g++ blocking_tcp_echo_server.cpp -std=c++11 -lboost_system -lboost_thread -pthread
So far, everthing works fine.
But if you replace the boost::thread with std::thread (and #include ), the program will crash(terminated) when it access sock member ( socket::read_some() ).
Error message: terminate called without an active exception.
Any idea?

That's the difference between boost::thread and std::thread. I have seen the code, and you can fix it to work with std::thread, just like this:
void server(boost::asio::io_service& io_service, short port) {
// ...
std::thread t(boost::bind(session, sock));
t.detach();
}
It seems you must detach or join the thread when you use std::thread.
Code:
#include <iostream>
#include <thread>
int main(void) {
std::thread t([](){std::cout << "will throw exception" << std::endl;});
// t.detach();
return 0;
}
It will throw exception if not detach or not join or not link pthread

Related

Why does exception of one thread stop the whole process

I was told if one thread got some error, the whole process would be stopped. I used the c++11 code as below to do a simple test:
#include <iostream>
#include <thread>
#include <chrono>
void func1()
{
std::this_thread::sleep_for(std::chrono::seconds(5));
std::cout<<"exception!!!"<<std::endl;
throw(std::string("exception"));
}
void func2()
{
while (true)
{
std::cout<<"hello world"<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
int main()
{
std::thread t1(func1);
std::thread t2(func2);
t1.join();
t2.join();
return 0;
}
I compiled (g++ -std=c++11 -lpthread test.cpp) and executed it.
5 seconds later, I did get an error: Aborted (core dumped)
In my opinion, each thread has it own stack. In this example, if the stack of t1 dies, why can't the t2 continue?
As a thread only has its stack as private, all other things (heap, bss, data, text, env) are shared between threads. One thread crash will lead to the whole process crash, so t1 affected t2 in your program.

Why c++11 thread crash?

Look the code:
#include <iostream>
#include <thread>
using namespace std;
void task(int index){
cout<<index<<endl;
}
int main()
{
thread t1(task,1);
thread t2(task,2);
t1.join();
t2.join();
return 0;
}
The most time, the program runs normally, but sometimes it crashs? Why does it crash? I use C++11 thread in windows7, codeblocks.
The error is:
Assertion failed: ((m_->valid == LIFE_MUTEX) && (m_->busy > 0)), file C:/crossdev/src/winpthreads-git20141130/src/mutex.c, line 57

C++11 std::thread segment fault

This program ended with segment fault. Why ?
#include <thread>
void f(){}
int main(){
while(true){
std::thread t(f);
t.join();
}
}
environment: winxp+mingw+gcc4.8
The program should not cause any resource problem, for at the end of each loop, the thread finishes its execution and the thread object is destroyed.
I ran the slightly modified code below on Win 7 64 bit compiled with VS 2013 Update 3. While I was typing this answer, the counter reached more than 880,000 without any error. Therefore, the problem may be with your environment.
#include <thread>
#include <iostream>
void f(){}
int main(){
int i = 0;
while (true){
std::thread t(f);
t.join();
std::cout << ++i << std::endl;
}
}

std::thread C++ 11 fails to explain me why

I am running this very simple program, on Ubuntu 13.04 Desktop, however if I comment out the line sleep_for, it hangs after printing cout from main. Can anyone explain why ? As far as I understand, main is a thread and t is another thread and in this case the mutex manages synchronization for shared cout object.
#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
std::mutex mu;
void show()
{
std::lock_guard<mutex> locker(mu);
cout<<"this is from inside the thread"<<endl;
}
int main()
{
std::thread t(show);
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
std::lock_guard<mutex> locker(mu);
cout<<"This is from inside the main"<<endl;
t.join();
return 0;
}
If you change to main function as follows, the code will work as expected:
int main()
{
std::thread t(show);
{
std::lock_guard<mutex> locker(mu);
cout << "This is from inside the main" << endl;
} // automatically release lock
t.join();
}
In your code, there is a unfortunate race condition. If the thread t gets the lock first, everything works fine. But if the main threads gets the lock first, it holds the lock until the end of the main function. That means, the thread t has no chance to get the lock, can't finish and the main thread will block on t.join().
That's just a classic deadlock: The main thread obtains the lock and then blocks on joining the other thread, but the other thread can only join if it manages to obtain the lock.

Try...catch causes segmentation fault on embedded ARM with posix threads

Today, I posted a problem about a segmentation fault after destruction of a std::string (see this post). I've stripped the code so that I don't use the STL and still have a segmentation fault sometimes.
The following code works just fine on my PC running Linux. But using the ARM crosscompiler suppplied by the manufactor of our embedded device, it gives a segmentation fault just before catch (...).
This problems seems to have a link with this post in Google Groups, but I haven't found any solution yet.
The code is compiled using an ARM cross compiler
Any suggestions are still welcome!
#include <stdlib.h>
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
void *ExecuteThreadMethod(void *AThread);
class Thread
{
private:
pthread_t internalThread;
public:
void RunSigSegv()
{
try
{
for (int i = 0; i < 200; i++)
{
usleep(10000);
}
} // <---- Segmentation fault occurs here
catch(...)
{
}
}
void Start()
{
pthread_attr_t _attr;
pthread_attr_init(&_attr);
pthread_attr_setdetachstate(&_attr, PTHREAD_CREATE_DETACHED);
pthread_create (&internalThread, &_attr, ExecuteThreadMethod, this);
}
};
void *ExecuteThreadMethod(void *AThread)
{
((Thread *)AThread)->RunSigSegv();
pthread_exit(NULL);
}
Thread _thread1;
Thread _thread2;
Thread _thread3;
Thread _thread4;
void s()
{
_thread1.Start();
_thread2.Start();
_thread3.Start();
_thread4.Start();
}
int main(void)
{
s();
usleep(5000000);
}
I once encountered a problem like this which was caused by linking with a version of libstdc++ with no threading support, meaning that all threads shared a common exception handling stack with disastrous consequences.
Make sure the cross-compiler and its libraries were configured with --enable-threads=posix.
Just a diagnostic question: What happens if you don't detach the thread in Start()? You'd have to pthread_join() the threads back in main().
Also, have you considered Boost's threads? That might be more appropriate since you're using C++ rather than C.

Resources