我必须测试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()
现在,由于
calcFak()
函数中的threadjoin()
语句,您正在按顺序计算所有内容。因此,现在执行的函数实际上与下面的代码相同:正如您所看到的,没有线程好处。相反,使用queues和辅助函数来细分程序的执行:
在上面的代码中,我们创建了一个队列,该队列保存工作函数要使用的数据。辅助函数获得
num
变量的锁,然后对其进行修改。一旦队列为空(这发生在我们使用q.join()
加入队列之后),我们就可以访问num
变量的最终值来确定该数字是否为素数相关问题 更多 >
编程相关推荐