Multithreading for IO-intensive, multi-threaded implementation of two ways, see the example below
Example:
Import threading
Class MyThread (threading. Thread):
def __init__ (self, args):
#使用super写法, rewrite directly in the way that the parent class. method
Super (MyThread, self). __init__ ()
Self.args = args
def run (self):
Print ("Start MyThread {0}". Format (Self.args))
def worker (N):
Print ("Start worker{0}". Format (n))
if __name__ = = "__main__":
#同多进程使用方法
For I in xrange (1, 6):
#使用threading. thread specifies functions and parameters, multithreaded execution
T1 = Threading. Thread (Target=worker, args= (i,))
#开始多线程执行
T1.start ()
T1.join ()
#重写threading. The Run method in thread implements multithreading
For x in Xrange (6, 11):
T2 = MyThread (x)
T2.start ()
T2.join ()
Output:
Start Worker1
Start Worker2
Start Worker3
Start Worker4
Start Worker5
Start MyThread 6
Start MyThread 7
Start MyThread 8
Start MyThread 9
Start MyThread 10
Multi-threaded lock
The two types of multi-threaded locks are described in the following two examples
Example:
Import threading
Import time
def worker (name, lock):
#with写法会自动获得锁并自动释放锁, with
With Lock:
Print ("Start {0}". Format (name))
Time.sleep (2)
Print ("End {0}". Format (name))
if __name__ = = "__main__":
#锁的实例化
Lock = Threading. Lock ()
T1 = Threading. Thread (Target=worker, args= ("Worker1", Lock))
T2 = Threading. Thread (Target=worker, args= ("Worker2", Lock))
T1.start ()
T2.start ()
Print ("Main End")
Output:
Start Worker1
Main end
End Worker1
Start Worker2
End Worker2
Example:
Import threading
Import time
def worker (name, lock):
#获取线程锁
Lock.acquire ()
#捕获异常
Try
Print ("Start {0}". Format (name))
Time.sleep (2)
Print ("End {0}". Format (name))
Except Exception as E:
Raise E
Finally
#释放线程锁
Lock.release ()
if __name__ = = "__main__":
#锁的实例化
Lock = Threading. Lock ()
T1 = Threading. Thread (Target=worker, args= ("Worker1", Lock))
T2 = Threading. Thread (Target=worker, args= ("Worker2", Lock))
T1.start ()
T2.start ()
Print ("Main End")
Output:
Start Worker1
Main end
End Worker1
Start Worker2
End Worker2
Python thread lock