读取某个对象的成员变量(比如整形的成员变量)和对成员变量赋值都需要加锁,
因为为了防止在成员变量没有完全赋值完成后(即A=100没有完成),变量值被其他线程读取。从而得到的是错误的值。

解决方案 »

  1.   

    n个线程同时读取时不用加锁,前提是这个时候没有线程写
    当前32位机器内,n个线程同时写32位数据(按32位对齐的数据)时也不用加锁,前提是这个时候没有线程读
    最麻烦就是n个线程同时读写一个变量(例如i++这样),这时需要加锁,解决方法可以先将变量加上 volatile关键字,然后使用InterlockedXXX之类api来交换变量的值附上psdk解释
    The interlocked functions provide a simple mechanism for synchronizing access to a variable that is shared by multiple threads. The threads of different processes can use this mechanism if the variable is in shared memory.
    Simple reads and writes to properly-aligned 32-bit variables are atomic. In other words, when one thread is updating a 32-bit variable, you will not end up with only one portion of the variable updated; all 32 bits are updated in an atomic fashion. However, access is not guaranteed to be synchronized. If two threads are reading and writing from the same variable, you cannot determine if one thread will perform its read operation before the other performs its write operation.Simple reads and writes to properly aligned 64-bit variables are atomic on 64-bit Windows. Reads and writes to 64-bit values are not guaranteed to be atomic on 32-bit Windows. Reads and writes to variables of other sizes are not guaranteed to be atomic on any platform.The interlocked functions should be used to perform complex operations in an atomic manner. The InterlockedIncrement and InterlockedDecrement functions combine the operations of incrementing or decrementing the variable and checking the resulting value. This atomic operation is useful in a multitasking operating system, in which the system can interrupt one thread's execution to grant a slice of processor time to another thread. Without such synchronization, one thread could increment a variable but be interrupted by the system before it can check the resulting value of the variable. A second thread could then increment the same variable. When the first thread receives its next time slice, it will check the value of the variable, which has now been incremented not once but twice. The interlocked variable-access functions protect against this kind of error.
      

  2.   

    没有人发表意见的原因可能是你不给分吧~~~
    hoho
      

  3.   

    使用InterlockedXXX类的API,还需要加volatile关键字么?因为InterlockedXXX不就是使用操作成为原子操作么?加volatile关键字有什么作用呢?
      

  4.   

    ls的小朋友,你看看psdk内InterlockedXXX之类的函数原形再发表你的理论行不行
    LONG InterlockedIncrement(
      LONG volatile* Addend
    );
      

  5.   

    volatile关键字是防止编译器的过度优化,例如防止把一个auto变量优化成register变量,因为一条线程的register变量改变(没有写回到主存)并不会影响另一条线程的register变量,这样就失去了共享变量的性质了。
    还是那句
    交流交流