Last active
November 12, 2018 12:07
-
-
Save kgbook/25fcca13e052ede22826c69daebb393d to your computer and use it in GitHub Desktop.
[boost thread interrupt]example of boost::thread interruption #interrupt #multithreading #boost
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <boost/chrono/chrono.hpp> | |
#include <boost/thread/thread.hpp> | |
#include <unistd.h> | |
#include <sys/wait.h> | |
#include <sys/types.h> | |
static pid_t child_pid = 0; | |
void child_process_thread_func() { | |
std::cout <<__func__ <<", hello..." <<std::endl; | |
while (1) { | |
try { | |
boost::this_thread::sleep_for(boost::chrono::seconds(1)); | |
std::cout <<__func__<<", thread alive!" <<std::endl; | |
} catch (boost::thread_interrupted&) { | |
std::cout <<__func__ <<", thread terminated!" <<std::endl; | |
return ; | |
} | |
} | |
} | |
void reclaim_child_process() { | |
while (1) { | |
pid_t reclaim_pid = waitpid(child_pid, nullptr, 0); | |
if (reclaim_pid < 0) { | |
if (ECHILD == errno) { | |
std::cout <<__func__ <<", all child process terminated!" <<std::endl; | |
break; | |
} else { | |
std::cout <<__func__ <<", waitpid failed, " <<strerror(errno) <<std::endl; | |
continue; | |
} | |
} | |
std::cout <<__func__ <<", pid: " <<reclaim_pid <<" terminated!" <<std::endl; | |
} | |
} | |
int main(int argc, char **argv) { | |
boost::thread my_thread; | |
pid_t pid = fork(); | |
switch (pid) { | |
case 0: { | |
child_pid = getpid(); | |
std::cout <<"child process! pid:" <<getpid() <<std::endl; | |
my_thread = boost::thread(child_process_thread_func); | |
/* if uncomment this line, my_thread will not interrupt until child process is going to die */ | |
// my_thread.detach(); | |
break; | |
} | |
case -1: { | |
std::cerr <<"fork failed, " <<strerror(errno) <<std::endl; | |
break; | |
} | |
default: { | |
child_pid = pid; | |
std::cout <<"parent pid:" <<getpid() <<", child process id: " << pid <<std::endl; | |
break; | |
} | |
} | |
if (child_pid == getpid()) { | |
boost::this_thread::sleep_for(boost::chrono::seconds(3)); | |
my_thread.interrupt(); | |
my_thread.join(); | |
} else { | |
reclaim_child_process(); | |
} | |
std::cout <<"pid: "<<getpid() <<" game over!" <<std::endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment