【问题标题】:Wait until all threads are started before run them等到所有线程都启动后再运行它们
【发布时间】:2016-09-03 07:06:02
【问题描述】:

我想对这部分脚本做同样的事情,但可能以不同的方式。可能吗?这个脚本等待所有线程都准备好并启动,然后运行 ​​urllib.request 的 while True ......既然我不想复制粘贴这个方法,有没有不同的方法来做到这一点?

import threading, urllib.request

class request(threading.Thread):
    def run(self):
        while nload:
            time.sleep(1)
        while True:
            urllib.request.urlopen("www.google.it")

nload = 1

for x in range(800):
    request().start()
    time.sleep(0.003)
    print "Thread " + str(x) + " started!"

print "The cycle is running..."
nload = 0
while not nload:
    time.sleep(1)

【问题讨论】:

    标签: python multithreading python-3.x


    【解决方案1】:

    更好的方法是使用threading.Event 对象。

    import threading, urllib.request
    
    go = threading.Event()
    
    class request(threading.Thread):
        def run(self):
            go.wait()
            while True:
                urllib.request.urlopen("www.google.it")
    
    for x in range(800):
        request().start()
        time.sleep(0.003)
        print "Thread " + str(x) + " started!"
    
    print "The cycle is running..."
    go.set()
    

    这保证了在调用go.set() 之前,没有线程会超过go.wait() 行。它不能确保 800 个线程在完全相同的时刻唤醒,因为您的 CPU 内核数量、操作系统的调度程序、python 的 GIL 以及可能我不知道的许多其他事情会阻止您拥有它控制程度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-24
      • 1970-01-01
      • 1970-01-01
      • 2015-10-04
      • 1970-01-01
      • 2011-12-17
      • 2011-01-31
      相关资源
      最近更新 更多