Repository navigation
Threading
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 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. It has an instruction pointer that keeps track of where within its context is it currently running.
- It can be pre-empted (interrupted).
- It can temporarily be put on hold (also known as sleeping) while other threads are running (this is called yielding).
There are two different kind of threads:
- kernel thread
- user thread
Kernel Threads are a part of the operating system, while the User-space threads are not implemented in the kernel.
There are several modules which support the usage of threads in Python. The best module is threading. The newer threading module provides much more powerful, high-level support for threads than the other modules.
The threading module exposes all the methods of other modules 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.
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:
-
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.
To implement a new thread using the threading module, you have to do the following:
- Define a new subclass of the Thread class.
- Override the
__init__(self [,args])method to add additional arguments. - Then, override the
run(self [,args])method to implement what the thread should do when started.
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 the run() method.
Eample 1:
#!/usr/bin/python3
import threading
import time
exitFlag = 0
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)
print_time(self.name, self.counter, 5)
print ("Exiting " + self.name)
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print ("%s: %s" % (threadName, time.ctime(time.time())))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
thread1.join()
thread2.join()
print ("Exiting Main Thread")Output:
Starting Thread-1
Starting Thread-2
Thread-1: Sun Aug 12 22:48:12 2018
Thread-2: Sun Aug 12 22:48:13 2018
Thread-1: Sun Aug 12 22:48:13 2018
Thread-1: Sun Aug 12 22:48:14 2018
Thread-2: Sun Aug 12 22:48:15 2018
Thread-1: Sun Aug 12 22:48:15 2018
Thread-1: Sun Aug 12 22:48:16 2018
Exiting Thread-1
Thread-2: Sun Aug 12 22:48:17 2018
Thread-2: Sun Aug 12 22:48:19 2018
Thread-2: Sun Aug 12 22:48:21 2018
Exiting Thread-2
Exiting Main Thread
Example 2:
#!/usr/bin/python3
import threading
import time
import random
def Thread_execution(i):
print("Execution of Thread {} started".format(i))
sleepTime = random.randint(1,4)
time.sleep(sleepTime)
print("Execution of Thread {} finished".format(i))
for i in range(4):
thread = threading.Thread(target=Thread_execution, args=(i,))
thread.start()Output:
Execution of Thread 0 started
Execution of Thread 1 started
Execution of Thread 2 started
Execution of Thread 3 started
Execution of Thread 1 finished
Execution of Thread 2 finished
Execution of Thread 0 finished
Execution of Thread 3 finished
In terms of computing, daemon is a background process that handles the requests for various services such as data sending, file transfers, etc. Following is the implementation of daemon threads in python.
Example:
import threading
import time
def daemonThread():
for i in range (20):
print("This is a daemon thread")
time.sleep(1)
if __name__ == '__main__':
daemonThread = threading.Thread(target = daemonThread)
daemonThread.setDaemon(True)
daemonThread.start()