Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Simple threaded counters (parameterized)

The same as the previous one, but with parameters controlling the numbers of threads and the range of the counter.

import threading
import sys

num_threads, count_till = 3, 5

class ThreadedCount(threading.Thread):
    def run(self):
        thread = threading.current_thread()
        print(f'{thread.name} - start')
        for cnt in range(count_till):
            print(f'{thread.name} - count {cnt}')
        print(f'{thread.name} - end')
        return

threads = []
for ix in range(num_threads):
    threads.append(ThreadedCount())

for th in threads:
    th.start()

print('main - running {} threads'.format(threading.active_count()))

for th in threads:
    th.join()
print("main - thread is done")
Thread-1 - start
Thread-1 - count 0
Thread-1 - count 1
Thread-1 - count 2
Thread-1 - count 3
Thread-1 - count 4
Thread-1 - end
Thread-2 - start
Thread-2 - count 0
Thread-2 - count 1
Thread-2 - count 2
Thread-2 - count 3
Thread-2 - count 4
Thread-2 - end
Thread-3 - start
Thread-3 - count 0
Thread-3 - count 1
Thread-3 - count 2
Thread-3 - count 3
Thread-3 - count 4
Thread-3 - end
main - running 1 threads
main - thread is done