Python - Multithreaded Programming
Python - Multithreaded Programming
Python Programming
More Detail
60 Lectures 2 hours
Jason Cannon
More Detail
https://www.tutorialspoint.com/python/python_multithreading.htm 1/9
9/7/22, 5:07 PM Python - Multithreaded Programming
Edouard Renard
More Detail
Running several threads is similar to running several different programs concurrently, but with the
following benefits −
Multiple threads within a process share the same data space with the main thread and can
therefore share information or communicate with each other more easily than if they were
separate processes.
Threads 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. It has an instruction pointer
that keeps track of where within its context it is currently running.
It can temporarily be put on hold (also known as sleeping) while other threads are running -
this is called yielding.
This method call enables a fast and efficient way to create new threads in both Linux and
Windows.
The method call returns immediately and the child thread starts and calls function with the
passed list of args. When function returns, the thread terminates.
Here, args is a tuple of arguments; use an empty tuple to call function without passing any
arguments. kwargs is an optional dictionary of keyword arguments.
Example
#!/usr/bin/python
import thread
import time
count = 0
https://www.tutorialspoint.com/python/python_multithreading.htm 2/9
9/7/22, 5:07 PM Python - Multithreaded Programming
time.sleep(delay)
count += 1
try:
except:
while 1:
pass
Although it is very effective for low-level threading, but the thread module is very limited
compared to the newer threading module.
The threading module exposes all the methods of the thread module and provides some
additional methods −
threading.enumerate() − Returns a list of all thread objects that are currently active.
In addition to the methods, the threading module has the Thread class that implements
threading. The methods provided by the Thread class are as follows −
https://www.tutorialspoint.com/python/python_multithreading.htm 3/9
9/7/22, 5:07 PM Python - Multithreaded Programming
start() − The start() method starts a thread by calling the run method.
join([time]) − The join() waits for threads to terminate.
Once you have created the new Thread subclass, you can create an instance of it and then start
a new thread by invoking the start(), which in turn calls run() method.
Example
#!/usr/bin/python
import threading
import time
exitFlag = 0
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print_time(self.name, 5, self.counter)
while counter:
if exitFlag:
threadName.exit()
https://www.tutorialspoint.com/python/python_multithreading.htm 4/9
9/7/22, 5:07 PM Python - Multithreaded Programming
time.sleep(delay)
counter -= 1
thread1.start()
thread2.start()
Starting Thread-1
Starting Thread-2
Exiting Thread-1
Exiting Thread-2
Synchronizing Threads
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 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.
https://www.tutorialspoint.com/python/python_multithreading.htm 5/9
9/7/22, 5:07 PM Python - Multithreaded Programming
The release() method of the new lock object is used to release the lock when it is no longer
required.
Example
#!/usr/bin/python
import threading
import time
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
threadLock.acquire()
print_time(self.name, self.counter, 3)
threadLock.release()
while counter:
time.sleep(delay)
counter -= 1
threadLock = threading.Lock()
threads = []
thread1.start()
thread2.start()
threads.append(thread1)
threads.append(thread2)
https://www.tutorialspoint.com/python/python_multithreading.htm 6/9
9/7/22, 5:07 PM Python - Multithreaded Programming
for t in threads:
t.join()
Starting Thread-1
Starting Thread-2
get() − The get() removes and returns an item from the queue.
Example
#!/usr/bin/python
import Queue
import threading
import time
exitFlag = 0
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
https://www.tutorialspoint.com/python/python_multithreading.htm 7/9
9/7/22, 5:07 PM Python - Multithreaded Programming
process_data(self.name, self.q)
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
else:
queueLock.release()
time.sleep(1)
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1
thread.start()
threads.append(thread)
threadID += 1
queueLock.acquire()
workQueue.put(word)
queueLock.release()
pass
exitFlag = 1
for t in threads:
t.join()
https://www.tutorialspoint.com/python/python_multithreading.htm 8/9
9/7/22, 5:07 PM Python - Multithreaded Programming
Starting Thread-1
Starting Thread-2
Starting Thread-3
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
https://www.tutorialspoint.com/python/python_multithreading.htm 9/9