簡體   English   中英

我需要制作一個多線程程序(python)

[英]I need to make a multithreading program (python)

import multiprocessing
import time
from itertools import product
out_file = open("test.txt", 'w')
P = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p','q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',]
N = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
M = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
c = int(input("Insert the number of digits you want: "))  
n = int(input("If you need number press 1: "))               
m = int(input("If you need upper letters press 1: "))            
i = []
if n == 1:
    P = P + N
if m == 1:
    P = P + M
then = time.time()
def worker():
    for i in product(P, repeat=c):      #check every possibilities
        k = ''
        for z in range(0, c):           #
            k = k + str(i[z])           #   print each possibility in a txt without parentesis or comma
    out_file.write( k + '\n')           #
    out_file.close()
    now = time.time()
    diff = str(now - then)              # To see how long does it take
    print(diff)
worker()
time.sleep(10)                  # just to check console

代碼檢查每種可能性並將其打印在test.txt文件中。 它有效,但我真的無法理解如何加快速度。 我看到它使用了我的四核CPU中的1核,所以我認為多線程可能會工作,即使我不知道如何。 請幫我。 抱歉我的英語,我來自意大利。

您目前無法將此代碼並行化為當前狀態,原因很簡單。

你的工人職能中有競爭條件。 如果一個進程要關閉輸出文件,則任何需要打開文件的其他進程都會引發異常。

您有兩種方法可以解決此問題:

  1. 從函數中刪除文件關閉並將所有文件寫入包裝在互斥鎖中,以確保文件寫入一次只能由一個進程完成。

  2. 從worker函數中刪除所有文件訪問權限,並將其結果返回到數組中。 這樣,您可以並行運行多個工作程序,並在所有進程完成后整理結果。 這樣,您就可以在代碼末尾處理來自主線程/進程的所有文件訪問。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM