Your browser does not support JavaScript!
Upvotes Anonymous 4 User 0

Threads in Python 3

When writing programs, we often need a way to do multiple things simultaneously. An example of this is a web browser; if a page is taking forever to load, then users might open another tab and browse while they're waiting.

Threading is kind of like juggling:
where each ball is like a thread.
Python Code
Below is a program that creates two threads that count, starting at zero. We start the second counter a second after the first one starts.
import threading
import time

class Counter:
    def __init__(self, counter_num):
        self.counter_num = counter_num
        self.count = 0

    def counting_thread(self):
        while True:
            print('Counter {0}: {1}'.format(self.counter_num, self.count))
            self.count += 1

    def start(self):
        thread = threading.Thread(target=self.counting_thread)

counter = Counter(1)


counter2 = Counter(2)
The Results
The output is:
Counter 1: 0
Counter 1: 1
Counter 2: 0
Counter 1: 2
Counter 2: 1
Counter 1: 3
Counter 2: 2
Counter 1: 4
Counter 2: 3
Counter 1: 5
Counter 2: 4
Both counters are going at the same time, and the program runs indefinitely.
Beware of the GIL
The effects of Python's Global Interpreter Lock (GIL) are very important to understand. If you want to perform multiple processor-intensive tasks at once, you'll probably want to use multiprocessing. This is because the GIL limits your code to running on one thread. If you're doing things that won't fight for processing power, but instead are waiting tasks, such as requesting data from a server or waiting for the user to type something, then multi-threading is sufficient. 
Previous: Classes in Python
Was this helpful?



Leave a Comment

I agree to the Terms of Service
Design © 2015, Downranked, LLC.,
Original user code contributions under MIT License