I am new to using conditional_variables so I could easily be doing something stupid here but I am getting some odd performance when I use boost threads versus just calling the function directly. If I change the line that creates a boost thread on func to just call func directly, the code runs several orders faster. I have tried using the boost threadpool software off of source forge and it makes no difference...
Here is the code:
#include <boost/thread.hpp>
using namespace boost;
condition_variable cond;
mutex conditionalMutex;
int numThreadsCompleted = 0;
int numActiveThreads = 0;
void func()
{
{
lock_guard<mutex> lock(conditionalMutex);
--numActiveThreads;
numThreadsCompleted++;
}
cond.notify_one();
};
int main()
{
int i=0;
while (i < 100000)
{
if (numActiveThreads == 0)
{
++numActiveThreads;
thread thd(func);
//Replace above with a direct call to func for several orders of magnitude
//performance increase...
++i;
}
else
{
unique_lock<mutex> lock(conditionalMutex);
while (numThreadsCompleted == 0)
{
cond.wait(lock);
}
numThreadsCompleted--;
}
}
return 0;
}