Boost shared lock failed to create

时间:2017-08-05 11:27:17

标签: c++ boost locking

I have wrote some test code about boost shared mutex. I just found that sometimes boost::shard_lock maybe failed to create.

Did I misunderstood here? Or how to get the logs/exceptions?

const int thnum = 1000;
const int times = 10000;
long total = 0;

boost::shared_mutex shared_mutex_lock;

void shared_mutex_click() 
{
    for (int i = 0; i < times; ++i)
    {
        boost::shared_lock<boost::shared_mutex> readerLock(shared_mutex_lock);
        ++total;
    }
}

int main()
{
    boost::thread_group threads;
    clock_t start, end;
    total = 0;
    start = clock();
    for (int i = 0; i < thnum; ++i)
    {
        threads.create_thread(shared_mutex_click);
    }
    threads.join_all();
    end = clock();
    std::cout << "Shared Mutext Result: " << total << std::endl;
    std::cout << "Shared Mutext Time: " << end - start << std::endl;

    return 0;
}

While the test resule is: Shared Mutext Result: 7102861 Shared Mutext Time: 2451

It should be: Shared Mutext Result: 10000000

Right? why and how to figure out what happened, thanks.

1 个答案:

答案 0 :(得分:2)

The clue's in your variable names - you have a shared_lock called readerLock that you use to synchronise writes.

From the docs here, it seems your understanding of shared_lock is wrong. A shared_lock is designed to allow for multiple reading threads - but you're writing to the state instead. You want exclusive access in order to write, which means a unique_lock/lock_guard on your shared_mutex.

Edit: Also worth pointing out that since C++11, the core C++ libraries have some pretty nice synchronisation classes inspired by Boost's. I find the documentation on them easier to find/read, so if you're starting out learning and have access to a C++11 compiler, it might be worth using them instead.