python线程问题_Python线程问题
我有以下內容:
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.提前致謝.
解決方法:
Python(http://docs.python.org/2/library/threading.html)中的傳統線程在大多數常見的運行時受到“Global Interpreter Lock” (GIL)的限制,這可以防止多個線程同時執行,無論您擁有多少內核或CPU.盡管存在這種限制,但傳統線程在線程受I / O限制時仍然非常有價值,例如處理網絡連接或執行數據庫查詢,其中大多數情況下它們都在等待外部事件而不是“計算”.
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
來源: https://codeday.me/bug/20190723/1509479.html
總結
以上是生活随笔為你收集整理的python线程问题_Python线程问题的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: jsp中去掉超链接下划线吗_好烦啊,PP
- 下一篇: 麦芒5声音太小怎么升级