使用 Python 中的线程计算阶乘

Calculate factorials with threads in Python

我要测试 n = 17 是否是质数:(n-1)! mod n = n-1。首先,我必须计算 16 到 4 个线程的阶乘,这意味着间隔 1..16 必须分为 4 个子间隔:1..4、5..8、9..12、14 ..16。我通过16个线程测试了17是不是质数,一个线程一个操作,但是我不知道如何细分它使得操作只在4个线程中完成。

非常感谢一些想法,谢谢!

这是我的代码:

import threading

n = 17
t = n-1
ts = []
num = (n-1)/t
       
def calcFak():
    for i in range(t):
        c = i*(n-1)/t+1
        thread = threading.Thread(target=threads, args = (c,))
        ts.append(thread)
        thread.start()
        thread.join()
        

def threads(var):
    print(f"start thread {var}")
    global num
    num = num * var
    print(f"end thread {var}")

def managerThread(thread):
    calcFak()
    print(num)
    if num % n == t:
         print(n, ' is Prime')
    else:
         print(n, ' is not Prime')
    
    
t2 = threading.Thread(target = managerThread, args=(ts,))
t2.start()

由于 calcFak() 函数中的线程 join() 语句,现在您正在按顺序计算所有内容。因此,您现在执行的函数实际上与以下代码相同:

n = 17
t = n - 1
num = t/t

for i in range(t):
    c = i*t/t + 1
    print(f'Start {c}')
    num = num * c
    print(f'End thread {c}')

print(num)
if num % n == t:
    print(f'{n} is a prime number')
else:
    print(f'{n} is not a prime number')

如您所见,没有线程优势。相反,使用 queues 和辅助函数来细分程序的执行:

import threading
from queue import Queue
import time
n = 17
t = n - 1
num = t/t

# For threading
q = Queue()
num_lock = threading.Lock() # Lock so that no threads can overwrite our num value
threads = []                # List to store created threads

# Our worker gets items from the queue and processes them
def worker():
    global num
    while True:
        if not q.empty():
            c = q.get()
            num_lock.acquire()
            num = num * c
            num_lock.release()
            q.task_done()

for i in range(t):
    q.put(i*t/t + 1)

for thread in range(4):
    threads.append(threading.Thread(target=worker))
    threads[-1].daemon = True
    threads[-1].start()
    print('Made 1 thread')

q.join()

if num % n == t:
    print(f'{n} is a prime number')
else:
    print(f'{n} is not a prime number')

# Prints:
# Made 1 thread
# Made 1 thread
# Made 1 thread
# Made 1 thread
# 17 is a prime number

在上面的代码中,我们创建了一个队列来保存供辅助函数使用的数据。辅助函数锁定 num 变量,然后修改它。一旦队列为空(这发生在我们使用 q.join() 加入队列之后),我们然后访问 num 变量的最终值以确定数字是否为质数。