Can B thread can created in A thread?
After waiting for B thread end, Can A thread continue to run?
Can B thread can created in A thread?
After waiting for B thread end, Can A thread continue to run?
Short answer
There is very little conceptual difference between thread A and the main thread. Note that you could even join thread B in the main thread even though it was created from thread A.
Sample: (replace <thread>
with <boost/thread.hpp>
if you don't have a c++11 compiler yet)
#include <thread>
#include <iostream>
void threadB() {
std::cout << "Hello world\n";
}
void threadA() {
std::thread B(threadB);
B.join();
std::cout << "Continued to run\n";
}
int main() {
std::thread A(threadA);
A.join(); // no difference really
}
Prints
Hello world
Continued to run
If B is a child thread of A?
There are ways to synchronize threads for turn taking. Whether or not they can run in parallel depends on using kernel threads or user threads. User threads are not aware of different processors so they cannot run truly in 'parallel'. If you want the threads to take turns you can use a mutex/semaphore/lock to synchronize them. If you want them to run in true parallel you will need B to be a child process of A.
You can also end the child thread/process in which case the parent will be scheduled. It's often not possible to guarantee scheduling without some sort of synchronization.
void FuncA() {
if(ScanResultsMonitorThread == NULL) {
/* start thread A */
}
}
void FunAThread() {
while(1) {
FuncB();
}
}
void FuncB() {
try {
boost::this_thread::sleep(boost::posix_time::seconds(25));
}
catch(const boost::thread_interrupted&) {
}
if(needRestart){
/* create thread B */
boost::thread Restart(&FuncBThread,this);
boost::this_thread::sleep(boost::posix_time::seconds(10));
/* program can not run here and thread A end, why? */
}
else {
}
}