线程:第二个线程不并行运行



我第一次使用线程,但不知怎么的,它不起作用。当我启动第一个线程时,它启动了,但第二个线程没有。经过一点调试,我注意到问题在于,因为线程1有一个无限循环,所以另一个循环会等待,直到第一个循环停止。然而,我希望它们并行运行。

代码:

主脚本

com = Communication("RPI", "192.168.2.156")
water = Water(com)
t_com = threading.Thread(target= com.server())
t_water = threading.Thread(target=water.main())
if __name__ == '__main__':
print("Starting")
t_com.start()
t_water.start()

通讯:这里的程序陷入

class Communication:
def __init__(self, clientName, serverAddress):
print("Com")
self.mqttClient = mqtt.Client(clientName)
self.mqttClient.connect(serverAddress, 1883)
self.stunde = None
self.minute = None
self.active = False
self.time_to_water = None
self.dauer = None
def server(self): <!-- a necessary infinity loop -->
print("Thread1 activated")
self.mqttClient.on_connect = self.connectionStatus
self.mqttClient.on_message = self.messageDecoder
self.mqttClient.loop_forever()

水:这个线程没有启动,但应该

class Water:
def __init__(self, com):
print("Water")
self.sensoren = Sensoren(pinRain=22, pinVent1=17, pinVent2=27)
self.com = com
def main(self):
print("Thread2 activated")
while True:

在我的程序的第一个版本中,WaterCommunication不是类,而是许多函数的混合。以上代码在main.py中起作用。

创建线程时,目标参数上不应该有括号。您正在调用该函数,然后(在这种情况下,永远不会(将该函数的结果作为参数传递,相反,您应该传递要调用的函数(仅传递名称,没有括号(。

为了回答标题上的问题,由于全局解释器锁,Python解释器一次只允许执行一个线程,据我所知,它主要用于内存安全,但它不允许纯Python的真正并行性。您仍然可以使用多访问或编译的C函数(至少在CPython上(执行并行任务,因为这些任务可以绕过GIL,但您必须管理自己的锁,以防多个线程访问相同的数据。

https://en.wikipedia.org/wiki/Global_interpreter_lock

https://wiki.python.org/moin/GlobalInterpreterLock

https://realpython.com/python-gil/

https://www.youtube.com/watch?v=m2yeB94CxVQ

最新更新