Reputation: 1487
i'd like to do the same thing of this part of script, but possibly in a different way. Is it possible? This script waits that all threads are ready and started and then run the while True of urllib.request... Since I don't want to copy-paste this method, is there a different way to do it?
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)
Upvotes: 0
Views: 82
Reputation: 4691
A better way is to use a threading.Event object.
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()
This guarantees that no thread will advance past the go.wait()
line until go.set()
is called. It can't ensure that the 800 threads wake up at the exact same moment, since your number of CPU cores, your operating system's scheduler, python's GIL, and probably a lot of other things I don't know about prevent you from having that degree of control.
Upvotes: 1