Python: Threading specific number of times
<p>I have the following code that uses <code>threading</code> and prints the current count.</p>

<pre><code>import threading

count = 0
def worker():
    """thread worker function"""
    global count
    count += 1
    print(count)

threads = []
for i in range(5):
    t = threading.Thread(target=worker)
    threads.append(t)
    t.start()
</code></pre>

<p>It is currently set to 5 threads. How can I have it continue running the threads until it reaches a certain #. i.e. run at 5 threads until <code>worker()</code> has run 100 times.</p>

<p>To be honest, if you want something like this, it means that you are going to wrong direction. Because this code is <code>stateful</code> and <code>stateful</code> processing is far away from real parallel execution.
Also usually if you want to execute code in parallel in python, you need to use <a href="https://docs.python.org/2/library/multiprocessing.html" rel="nofollow">multiprocessing</a> module.</p>

<p>So, basically, if you goal is to tick 100 times in total, it's better to rewrite your code in stateless way:</p>

<pre><code>import multiprocessing as mp

def worker_1(x):
  for i in range(x)
      print i

def worker_2(y):
   print y

if __name__ == '__main__':
  p = mp.Pool(5)

  for x in p.pool(worker_1, [25, 25, 25, 25]):
     // process result
     pass

  for y in p.pool(worker_2, range(100)):
     // process result
     pass
</code></pre>

python multithreading python-multithreading