我可以使用互锁操作来更新多个值以避免锁定关键部分/互斥体吗?
我有一个多线程应用程序(C++),我需要在其中增加/更改一系列值。 如果我使用一系列互锁操作,它们是否被视为单个原子操作? 就像这个例子一样:
InterlockedIncrement(&value1);
InterlockedIncrement(&value2);
InterlockedExchange(&oldValue, newValue);
或者我们用锁来执行同步会更好? 像这样:
EnterCriticalSection(&cs);
value1++;
value2++;
oldValue = newValue;
LeaveCriticalSection(&cs);
我认为需要一把锁,但我不确定......所有值要么处于旧状态,要么处于新状态,这一点非常重要。
I have a multithreaded application (C++) where I need to increment/change a series of values.
If I use a series of Interlocked operations, are they considered to be a single atomic operation ? Like in this example:
InterlockedIncrement(&value1);
InterlockedIncrement(&value2);
InterlockedExchange(&oldValue, newValue);
Or it would be better to us a lock to perform the synchronization ? Like this:
EnterCriticalSection(&cs);
value1++;
value2++;
oldValue = newValue;
LeaveCriticalSection(&cs);
I think a lock is required, but I'm not sure... it's very important that all the values to be either in the old state, or in the new one, together.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
InterlockedIncrement
本身是一个原子操作,但一系列InterLockedIncrement
在一起并不是原子操作。 如果您的要求是获得一系列操作的原子性,那么您可以使用临界区。InterlockedIncrement
itself is an atomic operation but series ofInterLockedIncrement
are not atomic together. If your requirement is to get the atomicity for series of operation then you can use critical section.如果必须完全执行这些值才能保持一致的状态,则需要使用临界区。 例如,如果您的价值观实际上类似于
并且您没有使用关键部分,那么您可能会遇到这样的情况:巴拉克·奥巴马 (Barack Obama) 担任总统,迪克·切尼 (Dick Cheney) 担任副总裁,如果您在两者之间发生某种中断或上下文切换这些语句的执行。 这种状态是不一致的,我想我们都会同意:)
但是,如果您正在做类似的事情
并且每个操作的结果都留下了完整的状态,那么互锁就可以了。
If the values must be fully executed to leave a consistent state, you will need to use the critical section. For example, if your values were actually something like
and you weren't using a critical section, you could be in a situation where Barack Obama was put in as President and Dick Cheney was VP if you had some kind of interruption or context switch between the execution of those statements. This state is inconsistent I think we would all agree :)
However, if you are doing something like
and the result of each operation left a complete state, the interlock will be fine.
您应该使用临界区来确保原子性。
You should use critical section to ensure atomicity.
您必须定义“状态”是什么。 看起来您希望所有三个变量都以原子方式更改 - 在这种情况下,三个单独的原子是不够的。 但是,如果您可以将所有状态分组到某种类型的对象中,那么您应该能够使用“交换指针”技术来更新状态。
You have to define what the "state" is. It looks like you want all three variables to change atomically - in this case three individual atomics are not enough. But if you can group all the state into an object of some sort, you should be able to use "swap a pointer" technique for updating state.
你是对的,因为所有的值要么处于旧状态,要么处于新状态; 你应该使用关键部分
You're right, since all the values to be either in the old state, or in the new one, together; you should use the Critical Section