Free Python course: Alyun University — Developer class

Threads are used in Python in two ways: functions or classes that wrap thread objects.

Function: Call start_new_thread() in the thread module to generate a new thread. The syntax is as follows:

thread.start_new_thread ( function, args[, kwargs] )Copy the code

Parameter Description:

Function-thread functions.

Args – The argument passed to the thread function. It must be of type tuple.

Kwargs – This parameter is optional.

Example:

#! /usr/bin/python# -*- coding: UTF-8
-*-import threadimport timeDef 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 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
Copy the code

The output of the above program is as follows:

Thread-1: Thu Jan 22 15:42:17 2009Thread-1:
Thu Jan 22 15:42:19 2009Thread-2: Thu Jan 22 15:42:19 2009Thread-1: Thu Jan 22
15:42:21 2009Thread-2: Thu Jan 22 15:42:23 2009Thread-1: Thu Jan 22 15:42:23
2009Thread-1: Thu Jan 22 15:42:25 2009Thread-2: Thu Jan 22 15:42:27
2009Thread-2: Thu Jan 22 15:42:31 2009Thread-2: Thu Jan 22 15:42:35 2009Copy the code

The termination of a thread usually depends on the natural termination of a thread function. You can also call thread.exit() from a thread function, which throws a SystemExit exception to exit the thread.



The threading module

Python provides support for threads through the two standard libraries Thread and threading. Thread provides a low-level, primitive thread and a simple lock.

Other methods provided by the Thread module:

Threading.currentthread (): returns the currentThread variable.

Threading.enumerate (): Returns a list of running threads. Running refers to the thread after starting and before ending, excluding the thread before starting and after ending.

Threading.activecount (): Returns the number of threads running as len(threading.enumerate()).

In addition to using methods, the Thread module also provides the Thread class to handle threads. The Thread class provides the following methods:

Run (): A method used to indicate thread activity.

Start (): starts thread activity.

Join ([time]): waits until the thread terminates. This blocks the calling thread until the thread’s join() method is aborted by calling it – either a normal exit or an unhandled exception thrown – or an optional timeout occurs.

IsAlive (): Returns whether the thread is active.

GetName (): Returns the thread name.

SetName (): Sets the thread name.



Create threads using the Threading module

Use the Threading module to create threads that inherit directly from threading.thread and override the __init__ and run methods:

#! /usr/bin/python# -*- coding: UTF-8
-*-import threadingimport time
exitFlag = 0class myThread
(threading.Thread):   Threading.thread
def __init__(self, threadID, name, counter):      
threading.Thread.__init__(self)       
self.threadID = threadID       
self.name = name       
self.counter = counter    def
run(self):                   The thread will run the run function directly after it is created
print "Starting " + self.name       
print_time(self.name, self.counter, 5)      
print "Exiting " + self.namedef print_time(threadName, delay,
counter):  
while counter:
if exitFlag:    
thread.exit()  
time.sleep(delay)    
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1Thread1 = myThread(1, "thread-1 ", 1);
"Thread-2", 2)# withdraw Thread thread1.start()thread2.start()print "Withdraw Main Thread"
Copy the code

The execution results of the above procedures are as follows;

Starting Thread-1Starting Thread-2Exiting
Main ThreadThread-1: Thu Mar 21 09:10:03 2013Thread-1: Thu Mar 21 09:10:04
2013Thread-2: Thu Mar 21 09:10:04 2013Thread-1: Thu Mar 21 09:10:05
2013Thread-1: Thu Mar 21 09:10:06 2013Thread-2: Thu Mar 21 09:10:06
2013Thread-1: Thu Mar 21 09:10:07 2013Exiting Thread-1Thread-2: Thu Mar 21
09:10:08 2013Thread-2: Thu Mar 21 09:10:10 2013Thread-2: Thu Mar 21 09:10:12 2013Exiting
Thread-2Copy the code

Thread synchronization

If multiple threads work together to modify data, unexpected results may occur. To ensure data correctness, multiple threads need to be synchronized.

Simple Thread synchronization can be achieved using Lock and Rlock of Thread objects, which both have acquire and release methods, and can be placed between acquire and Release methods for data that requires only one Thread at a time. As follows:

The advantage of multithreading is that you can run multiple tasks simultaneously (at least it feels that way). However, when threads need to share data, there can be data asynchronism.

Consider the case where all elements in a list are 0, the thread “set” changes all elements to 1 from back to front, and the thread “print” reads the list from front to back and prints.

So, maybe when the thread “set” starts changing, the thread “print” prints the list, and the output is half 0 and half 1, and that’s out of sync. To avoid this, the concept of locking was introduced.

Locks have two states — locked and unlocked. Whenever a thread such as “set” wants to access shared data, it must first acquire a lock; If another thread, such as “print”, has been locked, then the thread “set” is suspended, that is, synchronous blocking; Wait until the thread “print” is finished and the lock is released, then let the thread “set” continue.

After this processing, the list can be printed with either all zeros or all ones, without the awkward situation of half zeros and half ones.

Example:

#! /usr/bin/python# -*- coding: UTF-8
-*-import threadingimport timeclass myThread (threading.Thread):
def __init__(self, threadID, name, counter):      
threading.Thread.__init__(self)  
nbsp;  self.threadID =
threadID self.name = name self.counter = counter def run(self):    
print "Starting " + self.name       Return True if the lock is successfully acquired
# The optional timeout argument will block until a lock is obtained if left blank
Otherwise False will be returned after timeout
threadLock.acquire()
print_time(self.name, self.counter, 3)
# releases the lock
threadLock.release()def print_time(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1threadLock = threading.Lock()threads = []Create a new thread thread1
= myThread(1, "Thread-1", 1)thread2 = myThread(2,
"Thread-2", 2)Thread.append (thread1) Thread.append (thread2)#Wait for all threads to completefor t in threads:
t.join()print
"Exiting Main Thread"
Copy the code

Free Python course: Alyun University — Developer class