tcas
tcas

Reputation: 133

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:

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.

So if anyone knows the solution to my problem it would be very much appreciated.

Thanks in advance!

Upvotes: 1

Views: 4491

Answers (2)

Mark Tolonen
Mark Tolonen

Reputation: 177971

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. 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. Starting the thread will call that object with the tuple of args specified.

Upvotes: 7

sp________
sp________

Reputation: 2645

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()

Upvotes: 1

Related Questions