棘手的InterlockedDecrement与CriticalSection相关

And*_*rei 1 c++ winapi thread-safety

有全球long count反击.
线程A做

EnterCriticalSection(&crit);
// .... do something
count++;                       // (*1)
// .. do something else
LeaveCriticalSection(&crit);
Run Code Online (Sandbox Code Playgroud)

线程B的确如此

InterlockedDecrement(&count); // (*2) not under critical secion.
Run Code Online (Sandbox Code Playgroud)

在(*1),我处于一个关键部分.在(*2),我不是.

(*1)没有安全InterlockedIncrement()吗?(它是受保护的关键部分).
我需要InterlockedIncrement()(*1)吗?
我觉得我可以赞成和反对.

Cha*_*had 5

你应该使用其中一个,而不是混合它们.

虽然InterlockedDecrement保证是原子的,operator++但不是,虽然在这种情况下它可能取决于你的架构.在这种情况下,您实际上并没有实际保护count变量.

鉴于您似乎想要执行简单的inrecrement/decrement操作,我建议您只删除此情况下的关键部分并使用相关的Interlocked*函数.