Multi-Threading Questions
Multithreading Revision:-
Difference between multithreading and multitasking ?
Programs:-
1. Print 1 2 3 infinitely using threads in C
2. Maximum number of threads that can be created within a process in C
3. Print numbers in sequence using thread synchronization
4. Maximum number of Zombie process a system can handle
How you will handle exception before joining the threads, explain it in more detail.
What are benefits of using socket IPC ?
You can connect a simple client to them for testing (manually enter data, see the response). This is very useful for debugging, simulating and blackbox testing.
You can run the processes on different machines. This can be useful for scalability and is very helpful in debugging / testing if you work in embedded software.
It becomes very easy to expose your process as a service
How you will handle exception before joining the threads, explain it in more detail.
Refer the link for more detail
See this example:
class Player{
public:
auto playTask(){/**/}
auto play(){
// Thread inside class
std::thread t(&Player::playTask, this);
t.detach();
}
auto search(){/**/}
};
Player p;
// thread outside class
std::thread t(&Player::search, p)
Exception
Threads are not RAII, we need to join or detach a joinable thread at some point otherwise the program is terminated. This creates problems if an exception is thrown before joining:
auto task(){}
auto RunTask(){
std::thread t(task);
/* a code that may
throw exception */
t.join();
}
In the above code t.join()
is not reached if an exception is thrown before that. To solve this you can do this:
auto RunTask(){
std::thread t(task);
try{
/* a code that may
throw exception */
}
catch(...){
t.join();
throw;
}
t.join();
}
You can also create a RAII class that wraps std::thread
. When the class is destructed, it joins the thread automatically:
class RaiiThread {
private:
std::thread& t;
public:
RaiiThread(std::thread& _t ) : t(_t) {}
~RaiiThread() {
if(t.joinable())
t.join();
}
//Thread cannot be copied or assigned
RaiiThread(const RaiiThread &)= delete;
RaiiThread& operator=(const RaiiThread &)= delete ;
};
You can also create a RAII class that wraps std::thread
. When the class is destructed, it joins the thread automatically:
class RaiiThread {
private:
std::thread& t;
public:
RaiiThread(std::thread& _t ) : t(_t) {}
~RaiiThread() {
if(t.joinable())
t.join();
}
//Thread cannot be copied or assigned
RaiiThread(const RaiiThread &)= delete;
RaiiThread& operator=(const RaiiThread &)= delete ;
};
Comments
Post a Comment