This is a creation in Article, where the information may have evolved or changed.
Growing one small step a day is a big step in the accumulation.
In go, 15 threads are opened, and each thread increments the global variable traverse by 100,000 times, so the predicted result is 15*100000=1500000.
var sum intvar cccc intvar m *sync. Mutexfunc Count1 (i int, ch Chan int) {for J: = 0; J < 100000; J + + { CCCC = CCCC + 1 } ch <-cccc}fu NC Main () { m = new (sync. Mutex) ch: = Make (chan int, n) for I: = 0; i <; i++ { go Count1 (i, ch) } for I: = 0; i < 15 ; i++ { Select {case msg: = <-ch: fmt. PRINTLN (MSG)}}}
But the final result, 406527
Indicates that a lock needs to be added.
Func Count1 (i int, ch Chan int) { m.lock () for J: = 0; J < 100000; J + + { CCCC = CCCC + 1 } Ch <-CCCC m.unlock ()}
Final output: 1500000
Python: Not in the same way.
Count = 0def Sumcount (temp): global count for I in range (temp): count = count + 1li = []for i in range]:
th = Threading. Thread (Target=sumcount, args= (1000000,)) Th.start () li.append (TH) for i in Li: i.join () print (count)
Output results: 3004737
The instructions also need to be locked:
Mutex = Threading. Lock () Count = 0def Sumcount (temp): Global Count mutex.acquire () for I in range (temp): count = count + 1< C11/>mutex.release () Li = []for i in range]: th = Threading. Thread (Target=sumcount, args= (1000000,)) Th.start () li.append (TH) for i in Li: i.join () print (count)
Output 1500000
OK, lock the small.