简体   繁体   English

Python:同时执行多个无限循环

[英]Python: threading multiple infinite loops at the same time

In Python I am trying to get one infinite loop to start running parallel at the same time, a simple example would be: 在Python中,我试图使一个无限循环开始同时开始并行运行,一个简单的示例将是:

from threading import Thread

def func(argument):
    while True:
        print(argument)

def main():
    Thread(target=func("1")).start()
    Thread(target=func("2")).start()
    Thread(target=func("3")).start()
    Thread(target=func("4")).start()

if __name__ == '__main__':
    main()

Right now only the first thread runs, so the result is: 现在只有第一个线程运行,因此结果是:

1
1
1
1
....

And it should be: 它应该是:

1
2
3
4
....

I found several similar questions but none of the provided solutions seem to work for me, including using join on the threads. 我发现了几个类似的问题,但是所提供的解决方案似乎都不适合我,包括在线程上使用join

So if anyone knows the solution to my problem it would be very much appreciated. 因此,如果有人知道我的问题的解决方案,将不胜感激。

Thanks in advance! 提前致谢!

The first Thread isn't starting. 第一个线程未启动。 You are calling the func in main and attempting to set its return value as target , but it runs forever and the first Thread never gets created. 您正在main中调用func并尝试将其返回值设置为target ,但是它会永远运行并且永远不会创建第一个线程。 You want: 你要:

from threading import Thread

def func(argument):
    while True:
        print(argument)

def main():
    Thread(target=func,args=("1",)).start()
    Thread(target=func,args=("2",)).start()
    Thread(target=func,args=("3",)).start()
    Thread(target=func,args=("4",)).start()

if __name__ == '__main__':
    main()

This will pass func as an object. 这会将func作为对象传递。 Starting the thread will call that object with the tuple of args specified. 启动线程将使用指定的args元组调用该对象。

You can define your own thread: 您可以定义自己的线程:

from threading import Thread

class MyThread(Thread):
    def __init__(self,argument, **kwargs):
        super(MyThread, self).__init__(**kwargs)
        self.argument = argument

    def run(self):
        while True:
           print self.argument

if __name__ == '__main__':
    MyThread('1').start()
    MyThread('2').start()
    MyThread('3').start()
    MyThread('4').start()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM