I would like to launch 4 threads to do some work every 1 second in Python.
To make sure the work is done every 1 sec I inserted a sleep after the spawn as shown in the following code snippet. From printing it seems that the number of times do_work
was executed was 10 while I was expecting 10*4 --> the number of loop iterations x the number of threads. Also, it seems that the first thread starts to do the work after 4 seconds from the time printed in the main loop.(I printed the time also inside the thread).
run_pool = GreenPool(4)
counter = 0
while counter < 10:
run_pool.spawn(self.do_work)
time.sleep(1)
counter += 1
print time.time()
The parameter to the constructor for
GreenPool
is the number of worker threads that will be used. By passing the number 4, you are telling it to callself.do_work
by a maximum of four times simultaneously. Since you callspawn
ten times, you've queued up 10 "jobs", so that's how many timesdo_work
will get called. The amount of parallelism (4 in this case) doesn't affect the number of times your tasks get execute, but instead limits the amount of threads that may run simultaneously.