Threading
What is threading?
Light weight process
Benefits
Shared resources
Switching of threads
Efficient utilization of CPU etc.
Python Module
thread
Contents of the module ‘thread’ -
['LockType', '__doc__', '__name__', '__package__', '_count', '_local', 'allocate', 'allocate_lock', 'error',
'exit', 'exit_thread', 'get_ident', 'interrupt_main', 'stack_size', 'start_new', 'start_new_thread']
e.g. -
import thread
import time
# thread function
def print_time( threadName, delay):
count = 0
while count < 5:
time.sleep(delay)
count += 1
print "%s: %s" % ( threadName, time.ctime(time.time()) )
# Create threadds
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"
O/p -
Thread-1: Thu Aug 06 15:42:17 2013
Thread-1: Tue Aug 06 15:42:19 2013
Thread-2: Tue Aug 06 15:42:19 2013
Thread-1: Tue Aug 06 15:42:21 2013
Thread-2: Tue Aug 06 15:42:23 2013
Thread-1: Tue Aug 06 15:42:23 2013
Thread-1: Tue Aug 06 15:42:25 2013
Thread-2: Tue Aug 06 15:42:27 2013
Thread-2: Tue Aug 06 15:42:31 2013
Thread-2: Tue Aug 06 15:42:35 2013
Python Module
threading ( Part of Python 2.4 )
Content of Threading Module
['BoundedSemaphore', 'Condition', 'Event', 'Lock', 'RLock', 'Semaphore', 'Thread', 'ThreadError', 'Timer',
'_BoundedSemaphore', '_Condition', '_DummyThread', '_Event', '_MainThread', '_RLock',
'_Semaphore', '_Timer', '_VERBOSE', '_Verbose', '__all__', '__builtins__', '__doc__', '__file__', '__name__',
'__package__', '_active', '_active_limbo_lock', '_after_fork', '_allocate_lock', '_counter', '_enumerate', '_format_exc', '_get_ident', '_limbo', '_newname', '_pickSomeNonDaemonThread',
'_profile_hook', '_shutdown', '_sleep', '_start_new_thread', '_sys', '_test', '_time', '_trace_hook', 'activeCount', 'active_count', 'currentThread', 'current_thread', 'enumerate', 'local',
'setprofile', 'settrace', 'stack_size', 'warnings']
Content of Threading.Thread class
_Thread__bootstrap', '_Thread__bootstrap_inner', '_Thread__delete', '_Thread__exc_clear', '_Thread__exc_info',
'_Thread__initialized', '_Thread__stop', '__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_block', '_note', '_reset_internal_locks', '_set_daemon', '_set_ident', 'daemon', 'getName', 'ident', 'isAlive', 'isDaemon',
'is_alive', 'join', 'name', 'run', 'setDaemon', 'setName', 'start'
e.g. –
import threading
import time
exitFlag = 0
# inherit from threading.Thread class
class AvaneeshThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
# override the run() method
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name
# thread functionality method
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
thread.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
# Create new threads
thread1 = AvaneeshThread (1, "Thread-1", 1)
thread2 = AvaneeshThread (2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"
o/p -
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
Synchronization –
Need?
Available objects are - 'Event', 'Lock', 'RLock', 'Semaphore'
1. LOCK -
import threading
import time
class AvaneeshThread(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()
…
2. Semaphore –
Defined number of thread with accecc control mechanism.
maxconnections = 5
...
pool_sema = Semaphore(value=maxconnections)
pool_sema.acquire();
conn = connectdb();
... use connection ...
conn.close();
pool_sema.release();
3. RLock –
This is a special kind of Lock where a thread can utilise the Lock multiple times. So,
more than once acquire() and release() are called on the Lock.
This is used when recursive Lock.acquire() and Lock.Release() are called by a thread.
lock = threading.Lock()
lock.acquire()
lock.acquire() # the second acquire() will fail
lock = threading.RLock()
lock.acquire()
lock.acquire() # the second acquire() will not fail
4. Condition –
It denotes some state change and access of a thread can be controlled for
synchronisation.
# get the condition object
condition = threading.Condition()
#acquire the condition obj
condition.acquire()
# signal for any state change
condition.notify() # signal that a new item is available
# release the condition obj
condition.release()
Thread Pool / Queue -
Get a suitable datastructure like dict to hold worker threads created in advance for
any coming tasks.
e.g. – ATM applicaton
A priority system can be implemented and used with the thread pool functionalities.
e.g. –
Having priority field in customised thread class.
class AvaneeshThread(threading.Thread):
def __init__(self, threadID, name, counter, priority):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
self.priority = priority