c++ - Can a shared lock on a std::shared_timed_mutex be upgraded to an exclusive lock? -
c++ - Can a shared lock on a std::shared_timed_mutex be upgraded to an exclusive lock? -
the new std::shared_timed_mutex allows 2 types of locks: shared , exclusive.
if 1 holds shared lock, there way atomically exchange ("upgrade it") exclusive lock? in other words, given next code, how can avoid non-atomic drop , re-lock?
std::shared_timed_mutex m; //guards std::vector. m.lock_shared(); //read vector. (shared lock sufficient.) // ... //now want write vector. need exclusive lock. m.unlock_shared(); // <---- problem here: non-atomic! m.lock(); //write vector. // ... m.unlock(); ideally, m.unlock_shared(); m.lock(); replaced m.upgrade_to_exclusive(); (or boost::.upgrade_to_unique_lock()).
in similar question boost's shared_mutex dave s mentions
it impossible convert shared lock unique lock, or shared lock upgradeable lock without releasing shared lock first.
i'm not whether applies std::shared_mutex, though suspect does.
i happy reasonable work-around based on std::atomic/condition_variable or gcc's transactional memory.
edit: howard's reply addresses question. proposal n3427 contains nice descriptions of mechanism accomplish mutex upgrading. still welcome work-arounds based on std::atomic/condition_variable or gcc's transactional memory.
no, can not. functionality proposed commission under name upgrade_mutex , upgrade_lock, commission chose reject portion of proposal. there no work under way re-prepose functionality.
edit
in response "where go here" edit in user3761401's question, i've created partially crippled implementation of upgrade_mutex/upgrade_lock here:
https://github.com/howardhinnant/upgrade_mutex
feel free utilize this. in public domain. lightly tested, , not have total functionality described in n3427. next functionality missing:
one can not convertunique_lock shared_timed_lock. one can not try- or timed-convert shared_timed_lock unique_lock. one can not try- or timed-convert upgrade_lock unique_lock. that beingness said, i've included functionality in upgrade_mutex , can accessed @ low level in ugly manner (such examples in main.cpp).
the other lock conversions mentioned in n3427 available.
try- , timed-conversionsshared_timed_lock upgrade_lock. conversion upgrade_lock shared_timed_lock. blocking conversion upgrade_lock unique_lock. conversion unique_lock upgrade_lock. it has been set in namespace acme. set in whatever namespace want.
requirements
the compiler needs back upwards "rvalue-this" qualifiers, , explicit conversion operators.
disclaimers
the code has been lightly tested. if find bugs appreciate pull request.
it possible optimize upgrade_mutex through utilize of std::atomic. no effort has been done on front end (it hard , error prone task, taking more time have @ moment).
c++ multithreading c++11 c++14
Comments
Post a Comment