更多现代主题

时间:2019-03-10 11:29:48

标签: python multithreading

我正在尝试运行具有多个线程的代码,用户可以决定他要运行多少个线程。我尝试使用Python 3.7中的线程模块做到这一点

下面显示了我的代码,但是我的问题是,与其一起运行所有线程,而是一个接一个地运行...

import threading

x=int(input("Enter number of threads: "))

def main():
   print("My main function")
   print("Does some stuff...")
while x > 0:
    print("Starting Threads.")
    x=x-1       #At every time the while loops gets passed, x gets decremented, so once it hits 0 it stops

    t1=threading.Thread(target=main) #for every time the loop passes, a new thread gets created
    t1.start() #and the thread starts here

现在,我需要找出它们如何同时运行,而不是一个接一个地运行,我该怎么做。谢谢

1 个答案:

答案 0 :(得分:1)

您的代码并行运行(请注意:尽管仅在一个内核上运行;由于全局解释器锁定,这是python的限制)。

为了使其更明显,请稍微更改您的主要功能;现在的方式完成得太快了。我建议:

from time import sleep
from random import random

def main():
   print("main starting")
   sleep(random())
   print("main done")

这将输出类似

Enter number of threads: 4
Starting Threads.
main starting
Starting Threads.
main starting
Starting Threads.
main starting
Starting Threads.
main starting
main done
main done
main done
main done