Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/316.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在python线程中运行无限循环_Python_Multithreading_Python Multithreading - Fatal编程技术网

如何在python线程中运行无限循环

如何在python线程中运行无限循环,python,multithreading,python-multithreading,Python,Multithreading,Python Multithreading,我到处都找过了,看来我写的线索应该有用。我已经检查了很多关于它的其他线程和教程。我似乎无法在线程中运行无限循环。不管我怎么做,只有第一个线程工作/打印 下面是仅用于方法的代码 导入线程 def thread1(): 尽管如此: 打印(“abc”) def thread2(): 尽管如此: 打印(“123”) 如果名称=“\uuuuu main\uuuuuuuu”: t1=threading.Thread(目标=thread1()) t2=threading.Thread(目标=thread2()

我到处都找过了,看来我写的线索应该有用。我已经检查了很多关于它的其他线程和教程。我似乎无法在线程中运行无限循环。不管我怎么做,只有第一个线程工作/打印

下面是仅用于方法的代码

导入线程
def thread1():
尽管如此:
打印(“abc”)
def thread2():
尽管如此:
打印(“123”)
如果名称=“\uuuuu main\uuuuuuuu”:
t1=threading.Thread(目标=thread1())
t2=threading.Thread(目标=thread2())
t1.开始
t2.开始
t1.加入
t2.加入
使用
target=
调用函数结束时删除prentesse不会导致打印任何内容,因此我将其保留在那里

这是类/对象版本

从线程导入线程
1类螺纹(螺纹):
定义初始化(自):
线程。\uuuu初始化\uuuuu(自)
self.daemon=True
自我启动
def run():
尽管如此:
打印(“abc”)
螺纹2类(螺纹):
定义初始化(自):
线程。\uuuu初始化\uuuuu(自)
self.daemon=True
自我启动
def run():
尽管如此:
打印(“123”)
Thread1.run()
Thread2.run()
两者都无法打印
123
,我也不知道为什么。看起来无限循环不应该成为问题,因为它们是并行运行的。我尝试了
time.sleep
(bc可能是GIL idk停止了它),这样thread2可以在thread1空闲时运行。没用

对于第一个示例:

if __name__ == "__main__":
    t1 = threading.Thread(target=thread1)
    t2 = threading.Thread(target=thread2)

    t1.start()
    t2.start()

    t1.join()
    t2.join()
将函数(而不是调用函数的结果)传递到
threading.Thread
作为其
目标

对于本节示例。不要调用
run
。调用
start
。创建实例之后

from threading import Thread
class Thread1(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True

    def run():
        while True:
            print ("abc")

class Thread2(Thread):
    def __init__(self):
        Thread.__init__(self)
        self.daemon = True

    def run():
        while True:
            print ("123")

Thread1().start()
Thread2().start()

在第一个版本中,括号的位置不正确

正如当前编写的,在创建
t1
时,您正在传递调用
thread1
的结果;由于该调用永远不会返回,因此您永远不会实际创建线程。所以你需要去掉那些括号

但是您没有在试图调用
start
join
方法的地方包含括号,因此即使在创建线程时没有使用额外的括号,线程也从未真正启动过。

可能重复的