Why does exception of one thread stop the whole process - multithreading

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.

Related

Context switch doesn't accure to main thread in UNIX

I have a simpale program that should create two threads with a function hundler that will run infnite and a main thread.
Whenever I try to do pthread_join or pthread_exit to the main thread (in order to demonstrate that the children threads are still working after pthread_exit from main) there is never seems to be a context switch back to the main thread in order to print the message saying he is ending his job "Goodbye" (even the goodbye message before the thread creation is not printed, so I am not exactly sure what is the problem).Only the function handlers of the threads are printing what they should. I set sleep of 4 secs in the other threads in order to see this message before they start, there should have been a context switch to the only thread available that isn't sleeping (main)..
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
void *thread(void *vargp) {
sleep(4);
while(1)
printf("First Thread No' %ld\n",pthread_self());
}
void *thread2(void *vargp) {
sleep(4);
while(1)
printf("Second Thread No' %ld\n",pthread_self());
}
int main() {
int j,i = 42;
pthread_t tid, tid2;
printf("Good bye1");
pthread_create(&tid, NULL, thread, (void*)&i);
pthread_create(&tid2, NULL, thread2, (void*)&i);
printf("Good bye");
pthread_exit(NULL);
//pthread_join(tid, (void**)&i);
//pthread_join(tid2, (void**)&j);
}

C++11 thread detach not working

I understand that when a new thread is spawned it must be joined or detached else terminate shall be called, i have the below piece of code which work fine if i join them, but crashes if i call detach instead, I am not able to understand what's going on under the hood.
#include "iostream"
#include "thread"
#include "vector"
#include "algorithm"
#include "iterator"
#include "string"
#include "memory"
using namespace std;
void func() {
cout << " func ";
}
int main(int argc , char** argv)
{
std::vector< std::thread> m_vec;
for(int i = 0; i < 100 ; i++){
m_vec.push_back( std::thread(func));
m_vec[i].detach();
}
return 0;
}
Just detaching a thread doesn't give it permission to outlive the main thread. Once the main thread exits, that's the ballgame; the heap is destroyed, things like cout are cleaned up. Any remaining threads stand a distinct chance of crashing if they do anything before the process as a whole terminates.
If you detach a thread, be prepared to provide your own mechanism for ensuring it does not outlive the main thread.

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.

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

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

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