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>Loop it, of course.</p>

<pre><code>lock = threading.Lock()
count = 0
def worker():
    """thread worker function"""
    global count
    while True:
        with lock:
            if count &gt;= 100: break
            count += 1
            print(count)
</code></pre>

<p>Notice the protected access to <code>count</code> with <code>threading.Lock</code>; relying on <a href="https://en.wikipedia.org/wiki/Global_interpreter_lock" rel="nofollow">GIL</a> is sketchy.</p>

python multithreading python-multithreading