我开始学习python和多线程。我正在试着解决这个问题。我使用类哲学家(threading.thread)。但当我放入一些示例并创建线程时,它有一个错误AssertionError:group参数现在必须为None
import threading
import time
from random import randint
exitFlag = 0
class philosophers(threading.Thread):
def __int__(self, phi, hungry, eat):
threading.Thread.__int__(self)
#super(philosophers.self)__int__()
self.phi = phi
self.hungry = hungry
self.eat = eat
def hungry(self):
time.sleep(self.hungry)
print("Philosopher" +(self.phi) + "is hungry and want to eat" + "\n")
startEat()
def startEat(self):
left = self.phi
right = (self.phi+1)%5
left.acquire()
if right.locked():
left.release()
else:
right.acquire()
time.sleep(self.eat)
right.release()
left.release()
print("Philosopher" +(self.phi) + "is finished" + "\n")
#def run()
thread1 = philosophers(1, 5, 3)
thread2 = philosophers(2, 4, 2)
#thread3 = philosophers(3, 6, 7)
#thread4 = philosophers(4, 2, 8)
#thread5 = philosophers(5, 3, 4)
thread1.start()
thread2.start()
#thread3.start()
#thread4.start()
#thread5.start()
thread1.join()
thread2.join()
#thread3.join()
#thread4.join()
#thread5.join()
您的主要问题是简单的打字错误:它必须是
__init__
而不是__int__
(在两个地方)但还有其他问题
当您执行
thread.start()
时,它会在系统中创建线程并执行thread.run()
,所以您必须将def hungry
重命名为def run
left
和right
是正常数int
。不能将它们与acquire
、locked
、release
一起使用。为此需要对象threading.Lock这并没有错,但您可以将
threads
保留在列表中,然后在所有threads
上使用start()
和join()
就更简单了。即使更改列表中的threads
数,也不必更改这部分代码PEP 8 Style Guide for Python Code
最后一个问题是,我不确定你的算法是否正确
至于我
Philosopner
可以吃(time.sleep(self.eat)
),即使他没有两个叉子在开始时
left.acquire()
可以给出False
,但您不检查它编辑:
我添加了更多
print()
以查看变量中的值以及执行代码的哪一部分,我得到:还有
1 doesn't have forks
,3 doesn't have forks
但是他们不吃东西就吃完了可能需要一些循环来尝试再次获取分叉
编辑:
看来这个算法是正确的
结果:
相关问题 更多 >
编程相关推荐