How do I program using threads in Python


Threads are sometimes called light-weight processes and they do not require much memory overhead; they are cheaper than processes. A thread has a beginning, an execution sequence, and a conclusion.

There are two modules which support the usage of threads in Python3 −

  • _thread − Deprecated in Python 3

  • Threading − Introduced in Python 2.4

The threading Module

The newer threading module included with Python 2.4 provides much more powerful, high-level support for threads than the thread module.

The threading module exposes all the methods of the thread module and provides some additional methods −

  • threading.activeCount() − Returns the number of thread objects that are active.

  • threading.currentThread() − Returns the number of thread objects in the caller's thread control.

  • threading.enumerate() − Returns a list of all thread objects that are currently active.

The threading module has the Thread class that implements threading. The methods provided by the Thread class are as follows −

  • run() − The run() method is the entry point for a thread.

  • start() − The start() method starts a thread by calling the run method.

  • join([time]) − The join() waits for threads to terminate.

  • isAlive() − The isAlive() method checks whether a thread is still executing.

  • getName() − The getName() method returns the name of a thread.

  • setName() − The setName() method sets the name of a thread.

Program a Thread

The threading module provided with Python includes a simple-to-implement locking mechanism that allows you to synchronize threads. A new lock is created by calling the Lock() method, which returns the new lock.

The acquire(blocking) method of the new lock object is used to force the threads to run synchronously. The optional blocking parameter enables you to control whether the thread waits to acquire the lock. If blocking is set to 0, the thread returns immediately with a 0 value if the lock cannot be acquired and with a 1 if the lock was acquired. If blocking is set to 1, the thread blocks and wait for the lock to be released.

Example

The release() method of the new lock object is used to release the lock when it is no longer required.

import threading import time class myThread (threading.Thread): def __init__(self, threadID, name, counter): threading.Thread.__init__(self) self.threadID = threadID self.name = name self.counter = counter def run(self): print ("Starting " + self.name) # Get lock to synchronize threads threadLock.acquire() print_time(self.name, self.counter, 3) # Free lock to release next thread threadLock.release() def print_time(threadName, delay, counter): while counter: time.sleep(delay) print ("%s: %s" % (threadName, time.ctime(time.time()))) counter -= 1 threadLock = threading.Lock() threads = [] # Create new threads thread1 = myThread(1, "Thread-1", 1) thread2 = myThread(2, "Thread-2", 2) # Start new Threads thread1.start() thread2.start() # Add threads to thread list threads.append(thread1) threads.append(thread2) # Wait for all threads to complete for t in threads: t.join() print ("Exiting Main Thread")

Output

Starting Thread-1
Starting Thread-2
Thread-1: Mon Sep 19 08:57:59 2022
Thread-1: Mon Sep 19 08:58:00 2022
Thread-1: Mon Sep 19 08:58:01 2022
Thread-2: Mon Sep 19 08:58:03 2022
Thread-2: Mon Sep 19 08:58:05 2022
Thread-2: Mon Sep 19 08:58:07 2022
Exiting Main Thread

Updated on: 19-Sep-2022

159 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements