Use Threading. Thread class, there are three ways to create threads:
-
Create a thread class and pass it a function;
-
Create a thread class and pass it to a callable class object;
-
Derive a class from thread and create an instance of this subclass.
# Method 1 and Method 2 are created similar to Import threadingdef func (k): print (' thread %s replies %s '% (Threading.currentthread (). GetName (), k**2) ) if __name__ == ' __main__ ': mythreads = [] for i in range (1,5): t = Threading. Thread (target=func, args= (i,)) mythreads.append (t) print (' Start: ') for t in mythreads: t.start () #所以线程创建完后一起start instead of creating one that enables a for t in mythreads: t.join #等待所有线程运行完毕在继续执行主程序
# Method 3 was created by import Threadingclass Myclass (threading. Thread): def run (self): print (' I am Thread:%s '% (Self.getname ())) if __name__ = = ' __main__ ': Mythreads = [] For I in range (1,5): T = Myclass () mythreads.append (t) print (' Start: ') for T in Mythreads:t. Start () for T in Mythreads:t.join
The locking operation is not described here.
Python multi-thread threading module