在Python中使用线程计算阶乘

2024-09-30 02:22:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须测试n=17是否是质数:(n-1)!模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()

Tags: targetvardef线程threadstartnum质数
1条回答
网友
1楼 · 发布于 2024-09-30 02:22:31

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

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变量的最终值来确定该数字是否为素数

相关问题 更多 >

    热门问题