Why boost::shared_mutex cannot block more than 128 threads?

Viewed 99

Why boost::shared_mutex cannot block more than 128 threads? Is this a well-known issue?

boost1.67+mscv2015

    boost::shared_mutex mutex; 
    for (int i = 0; i < 256; i++)
    {
        std::thread([&]() {
                printf("begin\n");
                {    //crash after 128 times
                    boost::unique_lock<boost::shared_mutex> lock(mutex);
                    Sleep(5000);
                }
                printf("end\n");
            }).detach();
    }
    Sleep(5000);
1 Answers

I think it is implementation limitation. From /boost/thread/win32/shared_mutex.hpp:

namespace boost
{
    class shared_mutex
    {
    private:
        struct state_data
        {
            unsigned shared_count:11,
                shared_waiting:11,
                exclusive:1,
                upgrade:1,
                exclusive_waiting:7,
                exclusive_waiting_blocked:1;

            //...
        };
   // ...
   };
//...
}

See that exclusive_waiting is 7 bits, meaning it can only fit a value up to 127.

Think the idea is to make the state fit 32 bits to make it applicable to efficient atomic operation even for 32-bit windows process.

As for why it isn't larger for 64 bit - maybe for simplicity, or maybe it supports shared memory between 32 and 64 bit, not sure.

To work around the issue, consider std::shared_mutex, which is implemented on top of SRWLOCK, and does not suffer from this problem. Unless you need to support Windows XP, in this case not an option.

(Or, as a fix, consider avoiding the pattern that is not likely to be efficient anyway, as @sehe commented)

Related