[英]a code error about thread and process in python
在實踐python的線程和進程的時候,發現在處理一些函數的時候,線程和進程的打印結果會不一樣。 我不是很明白原因,所以我把代碼和打印結果一起發送了。 以及如何讓進程部分和線程部分的結果相同? 希望能得到幫助,謝謝
使用線程時,事情沒問題:
# coding:utf-8
import os, time, random, threading, multiprocessing
list = ['python', 'django', 'tornado', 'flask', 'bs5', 'requests', 'uvloop']
new_lists = []
def work():
if len(list) == 0:
return
data = random.choice(list)
list.remove(data)
new_data = '%s_new' % data
new_lists.append(new_data)
time.sleep(1)
if __name__ == '__main__':
start = time.time()
print('old list lenc is %s' % len(list))
for i in range(len(list)):
t = threading.Thread(target=work)
t.start()
t.join()
print('old list:', list)
print('new list', new_lists, len(new_lists))
print('time is %s' % (time.time() - start))
哪個將打印:(結果很好)
old list lenc is 7
old list: []
new list ['uvloop_new', 'python_new', 'bs5_new', 'tornado_new', 'django_new', 'requests_new', 'flask_new'] 7
time is 1.0153822898864746
但是,當將線程更改為進程時,發生了錯誤:
# coding:utf-8
import os, time, random, threading, multiprocessing
list = ['python', 'django', 'tornado', 'flask', 'bs5', 'requests', 'uvloop']
new_lists = []
def work():
if len(list) == 0:
return
data = random.choice(list)
list.remove(data)
new_data = '%s_new' % data
new_lists.append(new_data)
time.sleep(1)
if __name__ == '__main__':
start = time.time()
print('old list lenc is %s' % len(list))
for i in range(len(list)):
t = multiprocessing.Process(target=work)
t.start()
t.join()
print('old list:', list)
print('new list', new_lists, len(new_lists))
print('time is %s' % (time.time() - start))
哪個會打印:(結果不符合預期)
old list lenc is 7
old list: ['python', 'django', 'tornado', 'flask', 'bs5', 'requests', 'uvloop']
new list [] 0
time is 1.4266910552978516
提前謝謝~
在多線程中,您擁有共享內存,但在多處理中,您沒有共享內存。 因此,當您嘗試在每個進程中更改全局變量時,您會錯過數據。 這個問題沒有辦法這樣解決,你應該根據你的項目情況選擇正確的選項。 如果您需要在每個並行函數中操作共享數據,您應該使用線程。 盡管您可以使用 Queue 在多處理中的每個進程之間傳遞數據。 https://docs.python.org/3/library/queue.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.