We need to lock a .NET Int32 when reading it in a multithreaded code?

前端 未结 6 761
悲哀的现实
悲哀的现实 2020-12-23 23:38

I was reading the following article: http://msdn.microsoft.com/en-us/magazine/cc817398.aspx \"Solving 11 Likely Problems In Your Multithreaded Code\" by Joe Duffy

An

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-24 00:01

    It depends exactly how you're going to use the 32-bit number.

    If you wanted to perform an operation like:

    i++;
    

    That implicitly breaks down into

    1. reading the value of i
    2. adding one
    3. storing i

    If another thread modifies i after 1, but before 3, then you have a problem where i was 7, you add one to it, and now it's 492.

    But if you're simply reading i, or performing a single operation, like:

    i = 8;
    

    then you don't need to lock i.

    Now, your question says, "...need to lock a .NET Int32 when reading it..." but your example involves reading and then writing to an Int32.

    So, it depends on what you're doing.

提交回复
热议问题