gpt4 book ai didi

Python同时运行两个线程

转载 作者:行者123 更新时间:2023-11-30 23:24:10 30 4
gpt4 key购买 nike

是否可以同时运行两个线程?例如...

我有两个这样的类(class)...

import threading

class Thread1(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
print("Thread1")

class justAClass(object):
def do_soemthing(self):
print("Thread2")

if __name__ == "__main__":
total = 0
thread_limit = 200
while True:
if threading.activeCount() < thread_limit:
Thread1().start()
# I will never run because I want to wait until while True has finished to run!
t = threading.Timer(1.0, justAClass().do_soemthing())
t.start()

如果运行此代码,您将看到 Tread2永远不会被打印出来,因为 Thread2还得等Thread1完成(由于 While 语句,它永远不会完成。

我所追求的是两者Thread1Thread2同时运行,彼此独立。

最佳答案

while True:
if threading.activeCount() < thread_limit:
Thread1().start()
# I will never run because I want to wait until while True has finished to run!
t = threading.Timer(1.0, justAClass().do_soemthing())
t.start()

显然是这样的!由于您永远无法跳出循环,因此无法访问注释下方的代码。

不过,您的第一个代码是:

tor.connect()
tor.new_identity()

t = threading.Timer(10.0, tor.new_identity())
t.start()

total = 0
thread_limit = 200
while True:
if threading.activeCount() < thread_limit:
stress_test(host_ip, host_port).start()

您在无限循环之前启动了Timer,因此您的Timer线程肯定正在工作,正如我们在评论中所说。为了使您的 SSCCE 正常工作,修复如下:

import threading
import time

class Thread1(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
time.sleep(1)
print("Thread1")

class justAClass(object):
def do_something(self, pause):
while True:
time.sleep(pause)
print("Thread2XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

if __name__ == "__main__":
total = 0
thread_limit = 200
t = threading.Timer(1.0, justAClass().do_something, args=(1.0,))
t.start()
while True:
if threading.activeCount() < thread_limit:
Thread1().start()

但是,请注意,带有 do_something 函数的计时器线程只会运行一次,除非您从线程内重新配置它,或者在其中构建 while 循环。

顺便说一句,我修复了你的代码中的另一个错误,我一开始没有看到,你正在调用do_something 函数上的计时器,如果您传递 do_something 函数在 do_something() 末尾添加括号,它将在您的主线程中进行评估,因为您创建计时器,然后将函数的结果传递给 Timer函数...而如果您不使用括号,则您将给出函数对象本身到 Timer() ,然后可以在延迟后调用它。

is there a way to get the timer to run every x seconds while still allowing the other function to run?

当然:

class justAClass(object):
def do_something(self, pause):
while True:
time.sleep(pause)
print("Thread2XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")

关于Python同时运行两个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23596845/

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