2

我有一个信号量的实现来使用 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

4

0 回答 0