简体   繁体   中英

Run 1 subroutine multiple times simultaneously in threads in Python

I have a subroutine which I want to run over and over again, but in threads so it runs more times per second. I have tried using threading and using a while loop to run the threads again and again but you can't run one thread more than once.

Here is where I tried to create the threads realCode being my subroutine

checkerThread1 = Thread(name='T1', target=realCode, args=())
checkerThread2 = Thread(name='T2', target=realCode, args=())
checkerThread3 = Thread(name='T3', target=realCode, args=())
checkerThread4 = Thread(name='T4', target=realCode, args=())

while True:
    checkerThread1.start()
    checkerThread2.start()
    checkerThread3.start()
    checkerThread4.start()

I realise that this won't work, any alternatives would be appreciated.

Instead of directly using realCode as thread target, you could use a target that repeatedly calls it:

def repeat(function, *args):
    while True:
        function(*args)

for _ in range(4):
    Thread(target=repeat, args=[realCode]).start()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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