Acquire a lock on two mutexes and avoid deadlock

前端 未结 6 1145
清歌不尽
清歌不尽 2021-01-04 13:04

The following code contains a potential deadlock, but seems to be necessary: to safely copy data to one container from another, both containers must be locked to prevent cha

6条回答
  •  迷失自我
    2021-01-04 13:48

    this is a known problem already there is a std solution. std::lock() can be called on 2 or more mutex at the same time whilst avoiding deadlock's. More information here it does offer a recommendation.

    std::scoped_lock offers a RAII wrapper for this function, and is generally preferred to a naked call to std::lock.

    of course this doesn't really allow early releases of one lock above the other so use std::defer_lock or std::adopt_lock like I did in this answer to a similar question.

提交回复
热议问题