The threading module is provided in Python for multithreaded operations.
Multithreaded
Threads are the smallest unit of work in an application.
Multithreading is a reality in two ways:
Method 1: The construction method that will be executed passed to Thread as a parameter (similar to multiprocess)
t = threading.Thread(target=action, args=(i,))
Method 2: Inherit from Thread and override run()
Look at the source code:
P = threading.Thread
p.start() _start_new_thread(self.__bootstrap, ()) self.__bootstrap_inner()
self.run()
try:
if self.__target:
self.__target(*self.__args, **self.__kwargs)
So if you override run, you call the function of run directly, and if run is not rewritten, you call the target function.
Example:
import threading
def woker(n):
print ("start woker{0}".format(n))
class MyThread(threading.Thread):
def __init__(self,args):
super(MyThread,self).__init__()
self.args=args
def run(self):
print ("start Mythread{0}".format(self.args))
if __name__ =="__main__":
for i in xrange(1,3):
t1 = threading.Thread(target=woker,args=(i,))
t1.start()
t1.join()
for x in xrange(4,6):
t2=MyThread(x)
t2.start()
t2.join()
Result:
start woker1
start woker2
start Mythread4
start Mythread5
thread lock
adoptThreading.Lock() to create a lock, the function only executes to obtain the lock first, and then to release the lock after execution:
import threading
import time
def worker(name,lock):
with lock:
print ("start {0}".format(name))
time.sleep(3)
print ("stop {0}".format(name))
if __name__ == "__main__":
lock = threading.Lock()
t1 = threading.Thread(target=worker,args=("woker1",lock))
t2 = threading.Thread(target=worker,args=("woker2",lock))
t1.start()
t2.start()
print ("end main")
Result:
start woker1end main
stop woker1
start woker2
stop woker2