In C++, say I have a variable of basic data type, like int counter
, that is used by many threads. In order to modify counter
, a thread must obtain a simple lock first. But I want the value to be readable at any time, whether it is locked or not.
When a thread reads counter
while some other thread is modifying it, do I have any guarantee to at least get either the pre-write or post-write value, rather than some corrupted value?
For example:
//counter == 10
counter += 5;
//counter == 15
Will all threads reading counter
around this time be guaranteed to at least read 10
or 15
? Instead of some strange value like -834289
.
If the answer is implementation specific, I'm using Visual Studio 2015.
No it's not. Use a std::atomic_int
在Intel架构上 ,字大小值的分配通常是原子的,因此您不会读取损坏的值。
Look at the interlocked family of functions here:
https://msdn.microsoft.com/en-us/library/windows/desktop/ms686360(v=vs.85).aspx
The one you are looking for is most likely:
InterlockedAdd
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.