日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python与golang_Golang与python线程详解及简单实例

發布時間:2025/3/11 python 19 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python与golang_Golang与python线程详解及简单实例 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Golang與python線程詳解及簡單實例

在GO中,開啟15個線程,每個線程把全局變量遍歷增加100000次,因此預測結果是 15*100000=1500000.

var sum int

var cccc int

var m *sync.Mutex

func Count1(i int, ch chan int) {

for j := 0; j < 100000; j++ {

cccc = cccc + 1

}

ch

}

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 :=

fmt.Println(msg)

}

}

}

但是最終的結果,406527

說明需要加鎖。

func Count1(i int, ch chan int) {

m.Lock()

for j := 0; j < 100000; j++ {

cccc = cccc + 1

}

ch

m.Unlock()

}

最終輸出:1500000

python中:同樣方式實現,也不行。

count = 0

def sumCount(temp):

global count

for i in range(temp):

count = count + 1

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)

輸出結果:3004737

說明也需要加鎖:

mutex = threading.Lock()

count = 0

def 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,加鎖的小列子。

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

總結

以上是生活随笔為你收集整理的python与golang_Golang与python线程详解及简单实例的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。