简体   繁体   中英

run two thread concurrently and both of them manipulate single variable

it's my code:

import threading
x=0
class a(threading.thread)
    def run(self):
        global x
        for i in range(1000000):
             x+=1

class b(threading.thread)
    def run(self):
        global x
        for i in range(1000000):
             x-=1
def run():
    a().start()
    b().start()
    //after both thread done
    print x
run()

i expect this show me 0 (x=0) but every time i run it the result is pretty different(less than zero)
what's wrong with it?

Race conditions. The actual operation of x += 1 is roughly:

  1. Load the value of x
  2. Compute x + 1
  3. Store the computed value to x

Except with threading, you might get preempted by the other thread after step 1 and before step 3 (whether it's before or after 2 doesn't matter). If the other thread sees the unincremented value, decrements that, then you store your incremented value before it stores the decremented value, you just dropped an increment; if they store before you do, you dropped a decrement.

You need to lock access to shared variables to ensure that the operation behaves atomically:

import threading
x=0
xlock = threading.Lock()
class a(threading.Thread):
    def run(self):
        global x
        for i in range(1000000):
             with xlock:
                 x+=1

class b(threading.Thread):
    def run(self):
        global x
        for i in range(1000000):
             with xlock:
                 x-=1

This may introduce quite a bit of overhead, so other alternatives that touch the shared variable less may be better options (at the expense of having different behaviors).

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM