operation, statement and Interlocked
field comparison lock
volatile
Question:
Assume that a class contains a public type of counter field, which is accessed by multiple threads and only increases or reduced operations. Which method is the best way to increase this field, why?
int
lock(this.locker) this.counter ;
Change the counter decoration of the counter to Interlocked.Increment(ref this.counter);
public volatile
Change the counter decoration of the counter to
Only using fields cannot guarantee thread security. Although to ensure that multiple CPUs access the same data at the same time, it cannot prevent the interlacing of reading and writing operations, which may cause errors.
public volatile
volatile
volatile
The statement provides thread security by preventing other threads from performing the code of the protection field. However, the lock is relatively slow and may unnecessary to block other threads.
Best:
lock(this.locker) this.counter ;
lock
Comparison of operation and
The operation of the operation performed in the execution of a complete fence is used to prevent multiple CPUs from sorting.
Fields are placed around the semi -fence only around their operations, so they will not prevent re -sorting. Therefore, for the concurrent modification of the shared data, theInterlocked.Increment(ref this.counter);
The above is the detailed content of Which is the Optimal Approach for Incrementing a Shared Integer Counter Across Multiple Threads: `lock`, `Interlocked`, or `volatile`?. For more information, please follow other related articles on the PHP Chinese website!