python執行緒問題 Python執行緒問題

2021-10-12 12:14:00 字數 1255 閱讀 4133

我有以下內容:

d = #a dictionary with strings

l1 = [...] #a list with stuff

l2 = [...] #a list with numbers

for i in l1:

for key in l2:

#do some stuff

if d[key] == i:

print d[key]

我想使用執行緒(為了提高效能)做同樣的事情.我想的是:

import threading

d = #a dictionary with strings

l1 = [...] #a list with stuff

l2 = [...] #a list with numbers

def test(i, key):

#do the same stuff

if d[key] == i:

print d[j]

for i in l1:

for key in l2:

threading.start_new_thread(test, (i,key))

我不確定這是最好的方法.我擔心的是,我根本沒有優化.一些基本想法是:

> d應該在共享記憶體中(所有執行緒都可以訪問它).我假設沒有執行緒會訪問相同的條目.

>每個(i,key)組合應該同時進行測試.

如果你認為我應該使用另一種語言,如果你能指出它我會很高興.

幫助將是ayciated.提前致謝.

解決方法:

multiprocessing is a package that supports spawning processes using an

api similar to the threading module. the multiprocessing package

offers both local and remote concurrency, effectively side-stepping

the global interpreter lock by using subprocesses instead of threads.

due to this, the multiprocessing module allows the programmer to fully

leverage multiple processors on a given machine.

標籤:python,multithreading

python執行緒問題 Python執行緒問題

該樓層疑似違規已被系統摺疊 隱藏此樓檢視此樓 coding utf 8 import random import threading class mythread threading.thread def init self,func,args,name threading.thread.init ...

python 執行緒衝突問題

執行緒衝突問題 usr bin python coding utf 8 author fmspider time 2018 5 3 10 15 function 執行緒衝突 import threading def addnum global num num 1 tem num print ok n...

莫煩pytho學習之多執行緒

多執行緒是什麼呢?多執行緒是加速程式計算的有效方式,python的多執行緒模組threading上手快速簡單 新增執行緒 import threading defadding thread print this is new thread s threading.current thread def...