Can a shared lock on a std::shared_timed_mutex be upgraded to an exclusive lock?

前端 未结 1 1895
甜味超标
甜味超标 2021-02-05 04:09

The new std::shared_timed_mutex allows for two types of locks: shared and exclusive.

If one holds a shared lock, is there any way to atomically exchange it (\"upgrade it

1条回答
  •  攒了一身酷
    2021-02-05 05:03

    No, it can not. That functionality was proposed to the committee under the name upgrade_mutex and upgrade_lock, but the committee chose to reject that portion of the proposal. There is currently no work under way to re-prepose that functionality.

    Edit

    In response to the "where to go from here" edit in user3761401's question, I've created a partially crippled implementation of upgrade_mutex/upgrade_lock here:

    https://github.com/HowardHinnant/upgrade_mutex

    Feel free to use this. It is in the public domain. It is only lightly tested, and it does not have the full functionality described in N3427. Specifically the following functionality is missing:

    • One can not convert a unique_lock to a shared_timed_lock.
    • One can not try- or timed-convert a shared_timed_lock to a unique_lock.
    • One can not try- or timed-convert a upgrade_lock to a unique_lock.

    That being said, I've included this functionality in upgrade_mutex and it can be accessed at this low level in a very ugly manner (such examples are in main.cpp).

    The other lock conversions mentioned in N3427 are available.

    • try- and timed-conversions from shared_timed_lock to upgrade_lock.
    • conversion from upgrade_lock to shared_timed_lock.
    • blocking conversion from upgrade_lock to unique_lock.
    • conversion from unique_lock to upgrade_lock.

    It has all been put in namespace acme. Put it in whatever namespace you want.

    Requirements

    The compiler needs to support "rvalue-this" qualifiers, and explicit conversion operators.

    Disclaimers

    The code has been only lightly tested. If you find bugs I would appreciate a pull request.

    It is possible to optimize the upgrade_mutex through the use of std::atomic. No effort has been done on that front (it is a difficult and error prone task, taking more time than I have at the moment).

    0 讨论(0)
提交回复
热议问题