Golang and python thread details and simple examples, golangpython thread
Golang and python thread details and simple examples
In GO, 15 threads are enabled, and each thread increases global variable traversal by 100000 times. Therefore, the prediction 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}func main() { m = new(sync.Mutex) ch := make(chan int, 15) for i := 0; i < 15; i++ { go Count1(i, ch) } for i := 0; i < 15; i++ { select { case msg := <-ch: fmt.Println(msg) } }}
But the final result is 406527.
The lock is required.
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
In python: implementation in the same way does not work.
count = 0def sumCount(temp): global count for i in range(temp): count = count + 1li = []for i in range(15): th = threading.Thread(target=sumCount, args=(1000000,)) th.start() li.append(th)for i in li: i.join()print(count)
Output result: 3004737
It also requires locking:
mutex = threading.Lock()count = 0def sumCount(temp): global count mutex.acquire() for i in range(temp): count = count + 1 mutex.release()li = []for i in range(15): th = threading.Thread(target=sumCount, args=(1000000,)) th.start() li.append(th)for i in li: i.join()print(count)
1500000 output
OK, the lock column.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!