我有一个Semaphore实现来使用boost :: threads来管理共享资源。我对信号量的实现如下所示。
void releaseResource()
{
boost::unique_lock<boost::mutex> lock(mutex_);
boost::thread::id curr_thread = boost::this_thread::get_id();
// scan through to identify the current thread
for (unsigned int i=0; i<org_count;++i)
{
if (res_data[i].thread_id == curr_thread)
{
res_data[i].thread_id = boost::thread::id();
res_data[i].available = true;
break;
}
}
++count_;
condition_.notify_one();
}
unsigned int acquireResource()
{
boost::unique_lock<boost::mutex> lock(mutex_);
while(count_ == 0) { // put thread to sleep until resource becomes available
condition_.wait(lock);
}
--count_;
// Scan through the resource list and hand a index for the resource
unsigned int res_ctr;
for (unsigned int i=0; i<org_count;++i)
{
if (res_data[i].available)
{
res_data[i].thread_id = boost::this_thread::get_id();
res_data[i].available = false;
res_ctr = i;
break;
}
}
return res_ctr;
}
我的问题是当线程数多于可用资源数时,我注意到性能下降。如果我使用notify_all
来唤醒线程而不是notify_one
,如releaseResource()
代码中所示,我看到性能提高了。还有其他人经历过类似的事吗?
我正在使用 Windows 7 和提升1.52 。