Last active
June 27, 2017 02:20
-
-
Save bloodeagle40234/4f07c21fb98830be22ab487a7147b13e to your computer and use it in GitHub Desktop.
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
g++ easy_thread_pooling.cpp -o multi_thread -lboost_thread -lboost_system -lboost_chrono |
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 <boost/thread.hpp> | |
#include <boost/chrono.hpp> | |
#include <iostream> | |
void simple_thread(int id){ | |
std::cout << id << std::endl; | |
} | |
void longrun_thread(int id){ | |
std::cout << "long run launched" << std::endl; | |
int j; | |
for(double i=0; i<100000000; i++){ | |
j += i; | |
} | |
std::cout << "long run finished" << std::endl; | |
} | |
bool collectable(boost::thread* it){ | |
if(it->joinable()){ | |
if(it->try_join_for(boost::chrono::milliseconds(1))){ | |
delete it; | |
return true; | |
} | |
} | |
return false; | |
} | |
int main(){ | |
std::list<boost::thread*> thread_list; | |
const size_t limit = 5; | |
for(int i=0; i < 10; i++){ | |
while(thread_list.size() > limit){ | |
thread_list.remove_if(collectable); | |
std::cout << "resized to: " << thread_list.size() << std::endl; | |
} | |
thread_list.push_back(new boost::thread(&simple_thread, i)); | |
/*if(i == 0){ | |
thread_list.push_back(new boost::thread(&longrun_thread, i)); | |
}*/ | |
} | |
while(thread_list.size() > 0) thread_list.remove_if(collectable); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment