Pass parameters to threads - Counter with attributes



examples/threads/counter.py
import threading
import sys

class ThreadedCount(threading.Thread):
    def __init__(self, name, start, stop):
        super().__init__()
        self.name = name
        self.counter = start
        self.limit = stop
        print('__init__  of {} in {}'.format(self.name, threading.current_thread()))

    def run(self):
        print('start run of {} in {}'.format(self.name, threading.current_thread()))
        while self.counter < self.limit:
            print('count {} of {}'.format(self.name, self.counter))
            self.counter += 1
        print('end run   of {} in {}'
            .format(self.name, threading.current_thread()))
        return

foo = ThreadedCount("Foo", 1, 11)
bar = ThreadedCount("Bar", 1, 11)
foo.start()
bar.start()
print('main - running {} threads'.format(threading.active_count()))
foo.join()
bar.join()
print("main - thread is done")

__init__  of Foo in <_MainThread(MainThread, started 139645405484864)>
__init__  of Bar in <_MainThread(MainThread, started 139645405484864)>
start run of Foo in <ThreadedCount(Foo, started 139645391374080)>
count Foo of 1
count Foo of 2
start run of Bar in <ThreadedCount(Bar, started 139645382981376)>
count Bar of 1
main - running 3 threads
count Foo of 3
count Bar of 2
count Foo of 4
count Bar of 3
count Foo of 5
count Bar of 4
count Foo of 6
count Bar of 5
count Foo of 7
count Bar of 6
count Foo of 8
count Bar of 7
count Foo of 9
count Bar of 8
count Foo of 10
count Bar of 9
end run   of Foo in <ThreadedCount(Foo, started 139645391374080)>
count Bar of 10
end run   of Bar in <ThreadedCount(Bar, started 139645382981376)>
main - thread is done