Golang與python線程詳解及簡單實例
在GO中,開啟15個線程,每個線程把全局變量遍歷增加100000次,因此預測結果是 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) } }}
但是最終的結果,406527
說明需要加鎖。
func Count1(i int, ch chan int) { m.Lock() for j := 0; j < 100000; j++ { cccc = cccc + 1 } ch <- cccc m.Unlock()}
最終輸出:1500000
python中:同樣方式實現,也不行。
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)
輸出結果:3004737
說明也需要加鎖:
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
OK,加鎖的小列子。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
新聞熱點
疑難解答