I have a new 2 core CPU and I've been experimenting with boost::threads by attempting to keep both cores busy independent of each other.
Say I have a queue of 4 tasks to do. Each task will be handled by one thread. Some tasks will take longer to complete than others so I can't use thread_group with 2 threads at a time and join_all() as one core may finish before the other and set idle until the second thread completes. I use boost::thread::hardware_concurrency() to determine how many CPU cores I have available. My problem is *knowing* when a thread/CPU core finishes a task and is available for another task. Here is some sample code. I commented what I think would be an approach. Any suggestions or hints?
std::queue<std::string> string_queue()
{
std::queue<std::string> sq;
sq.push("AAA");
sq.push("BBB");
sq.push("CCC");
sq.push("DDD");
return sq;
}
void worker(std::string& S)
{
std::cout << S << std::endl;
}
int main()
{
std::cout << "Number of Cores: " << boost::thread::hardware_concurrency() << std::endl;
std::queue<std::string> strings = string_queue();
while ( !strings.empty() )
{
// if ( a CPU core is available )
// {
boost::thread t(boost::bind(&worker, strings.front()));
t.join();
strings.pop();
// }
// else
// {
// wait awhile and check if a CPU core is available again.
// }
}
return 0;
}
Hotmail: Trusted email with Microsoft’s powerful SPAM protection. Sign up now.