gpt4 book ai didi

Python 线程 : Multiple While True loops

转载 作者:行者123 更新时间:2023-12-03 12:44:09 25 4
gpt4 key购买 nike

你们对以下应用程序使用哪些 python 模块有任何建议:我想创建一个运行 2 个线程的守护进程,两个线程都使用 while True:循环。

任何例子将不胜感激!提前致谢。

更新:
这是我想出的,但行为不是我所期望的。

import time
import threading

class AddDaemon(object):
def __init__(self):
self.stuff = 'hi there this is AddDaemon'

def add(self):
while True:
print self.stuff
time.sleep(5)


class RemoveDaemon(object):
def __init__(self):
self.stuff = 'hi this is RemoveDaemon'

def rem(self):
while True:
print self.stuff
time.sleep(1)

def run():
a = AddDaemon()
r = RemoveDaemon()
t1 = threading.Thread(target=r.rem())
t2 = threading.Thread(target=a.add())
t1.setDaemon(True)
t2.setDaemon(True)
t1.start()
t2.start()
while True:
pass

run()

输出
Connected to pydev debugger (build 163.10154.50)
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon
hi this is RemoveDaemon

看起来当我尝试使用以下方法创建线程对象时:
t1 = threading.Thread(target=r.rem())
t2 = threading.Thread(target=a.add())
r.rem() 中的 while 循环是唯一被执行的。我究竟做错了什么?

最佳答案

当您创建线程时t1t2 ,你需要传递函数而不是调用它。当您调用 r.rem() ,在您创建线程并将其与主线程分开之前,它会进入无限循环。解决这个问题的方法是从 r.rem() 中删除括号。和 a.add()在你的线程构造函数中。

import time
import threading

class AddDaemon(object):
def __init__(self):
self.stuff = 'hi there this is AddDaemon'

def add(self):
while True:
print(self.stuff)
time.sleep(3)


class RemoveDaemon(object):
def __init__(self):
self.stuff = 'hi this is RemoveDaemon'

def rem(self):
while True:
print(self.stuff)
time.sleep(1)

def main():
a = AddDaemon()
r = RemoveDaemon()
t1 = threading.Thread(target=r.rem)
t2 = threading.Thread(target=a.add)

t1.setDaemon(True)
t2.setDaemon(True)
t1.start()
t2.start()
time.sleep(10)

if __name__ == '__main__':
main()

关于Python 线程 : Multiple While True loops,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42499299/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com