A Thread or a Thread of Execution is defined in computer science as the smallest unit that can be scheduled in an operating system. Threads are normally created by a fork of a computer script or program in two or more parallel (which is implemented on a single processor by multitasking) tasks. Threads are usually contained in processes. More than one thread can exist within the same process. These threads share the memory and the state of the process. In other words: They share the code or instructions and the values of its variables.
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.
There are two different kind of threads:
Kernel threads
User-space Threads or user threads
thread.start_new_thread ( function, args[, kwargs] )
import thread
import time
# Define a function for the thread
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create two threads as follows
try:
thread.start_new_thread( print_time, ("Thread-1", 2, ) )
thread.start_new_thread( print_time, ("Thread-2", 4, ) )
except:
print "Error: unable to start thread"
while 1:
pass
#Output
Thread-1: Tue Feb 05 14:19:40 2019
# Thread-2: Tue Feb 05 14:19:42 2019
# Thread-1: Tue Feb 05 14:19:42 2019
# Thread-1: Tue Feb 05 14:19:44 2019
# Thread-2: Tue Feb 05 14:19:46 2019
# Thread-1: Tue Feb 05 14:19:46 2019
# Thread-1: Tue Feb 05 14:19:48 2019
# Thread-2: Tue Feb 05 14:19:50 2019
# Thread-2: Tue Feb 05 14:19:54 2019
# Thread-2: Tue Feb 05 14:19:58 2019