Concurrency In C++

本文探讨了在多线程环境中安全删除节点的问题,分析了共享数据竞争条件的风险,并提出了避免死锁的建议。此外,还讨论了在没有使用锁的情况下如何通过线程间的调用来引发死锁。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 In order for a thread to safely delete a node, you need to ensure that you’re preventing concurrent accesses to three nodes: the node being deleted and the nodes on either side.


stack<int> s;
if(!s.empty())
{
    int const value=s.top();
    s.pop();
    do_something(value);
}



2 Not only is it safe in single-threaded code, it’s expected: calling top() on an empty stack is undefined behavior. With a shared stack object, this call sequence is no longer
safe, because there might be a call to pop() from another thread that removes the last element in between the call to empty() B and the call to top() c . This is therefore a Sharing data between threads classic race condition, and the use of a mutex internally to protect the stack contents doesn’t prevent it; it’s a consequence of the interface.


3 The common advice for avoiding deadlock is to always lock the two mutexes in the same order: if you always lock mutex A before mutex B, then you’ll never deadlock.


4 Deadlock doesn’t just occur with locks, although that’s the most frequent cause; you can create deadlock with two threads and no locks just by having each thread call
join() on the std::thread object for the other.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值