8. Three times class (December 13) 15.1 multithreaded instance 15.2 multithreaded lock

Eight three classes (December 13)

15.1 multithreading instance

Python provides the threading module to operate on multiple threads,
Multithreaded instance
Threads are the smallest unit of work in an application.

Multithreading is a reality in two ways:
Method 1: pass the method to be executed as a parameter to the Thread construction method (similar to multi process)

t = threading.Thread(target=action, args=(i,))

Method 2: inherit from Thread and override run()

See 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 rewrite run, you will call the function of run directly. If run is not renewed, you will call the target function.

Example

import threading

def worker(n):
    print("start worker{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 range(1,6):
        t1 = threading.Thread(target=worker,args=(i,))
        t1.start()
    t1.join()
    for x in range(6,11):
        t2 = MyThread(x)
        t2.start()
    t2.join()

result

start worker1
start worker2
start worker3
start worker4
start worker5
start MyThread6
start MyThread7
start MyThread8
start MyThread9
start MyThread10

15.2 multi thread lock

adopt threading.Lock() to create a lock. The function only needs to obtain the lock before executing, and release the lock after executing the left:

with lock: 
lock.acquire()
lock.release()

Example

import threading

import time

def worker(name,lock):
    with lock:
        print("start worker {0}".format(name))
        time.sleep(2)
        print("end worker {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")

Keywords: Python

Added by aquila125 on Fri, 29 May 2020 19:03:36 +0300