1. Thread
1) What is the thread
Thread operating system is the smallest unit of scheduling operations, are included in the process, a thread is a constant flow of execution
2. The relationship between threads and processes
Thread can not exist alone must exist in the process, the process is a resource unit, which contains all the resources needed to run the program, is the real thread of execution units
No threads, processes, resources can not be utilized, so a process that contains at least one thread, called the main thread, when we start a program, the operating system will create a main thread for yourself this program, the thread by the program can be late on, open your own thread called the child thread
3. Why do you need a thread
Only one purpose is to improve efficiency
4. multithreaded use
1) The way to use the module
2) Thread class inheritance, then override run () method
from threading import Thread,current_thread import time def task(): print("2",current_thread()) print("子进程running") time.sleep(10) print("子进程") if __name__ == '__main__': t=Thread(target=task) t.start() print("主线程") print("1",current_thread()) class myThread(Thread): def run(self): print("子进程tun") m=myThread() print("父进程")
5. Thread features
1) Create a small overhead
2) multiple threads in the same process data can be shared
Between 3) multi-threaded, is equal relationship, there is no parent-child relationship, PID all the threads are the same
# 创建线程开销对比 import os from threading import Thread from multiprocessing import Process import time def task(): # print("hello") print(os.getpid()) pass if __name__ == '__main__': st_time = time.time() ts = [] for i in range(100): t = Thread(target=task) # t = Process(target=task) t.start() ts.append(t) for t in ts: t.join() print(time.time()-st_time) print("主over")
6. daemon thread
You can set a thread as a daemon thread to another thread
Features: after the end of the thread is a daemon thread guard also come to an end
from threading import Thread import time def task(): print("子1running......") time.sleep(100) print("子1over......") def task2(): print("子2running......") time.sleep(4) print("子2over......") t = Thread(target=task) t.daemon = True t.start() t2 =Thread(target=task2) t2.start() print("主over")
Sharing means competition
Threads are also security issues,
Multiple threads can execute concurrently, and once a concurrent access to the same resources, there will be a problem
Solution: still mutex
from threading import Thread,enumerate,Lock import time number = 10 lock = Lock() def task(): global number lock.acquire() a = number time.sleep(0.1) number = a - 1 lock.release() for i in range(10): t = Thread(target=task) t.start() for t in enumerate()[1:]: # print(t) t.join() print(number)
Threading Lock Import from, current_thread, the Thread "" " deadlock when the program there has been more than a lock, which are held by a different thread, there is a resource must possess in order to use two locks this time the program will process unlimited stuck state, which is called a deadlock example: to eat plates and chopsticks but must have a person holding chopsticks another person holding chopsticks dish dishes such as how to avoid deadlock locks do not have more than an adequate if deadlock problem does occur, the party must be compelled to hand over the lock "" " Import Time # plate lock1 = lock () # chopsticks lock2 = lock () DEF eat1 (): lock1.acquire () Print ("% S grab to plate "% current_thread (). name) the time.sleep (0.5) lock2.acquire () Print ("% S chopsticks grab "current_thread% (). name) Print ("% S began eating! "% current_thread ( ).name) lock2.release() print ( "% s put down the chopsticks"% current_thread () name.) lock1.release () print ( "% s down plate"% current_thread () name.) DEF eat2 (): lock2.acquire () print ( "% s grab chopsticks "% current_thread (). name) lock1.acquire () Print ("% S to grab the plate "% current_thread (). name) Print ("% S open to eat! "% current_thread (). name) lock1 .release () Print ( "% S down plate"% current_thread (). name) lock2.release () Print ( "% S put down the chopsticks" current_thread% (). name) T1 = the Thread (target = eat1) T2 = the Thread (target = eat2) t1.start () t2.start ()
Rlock called reentrant or recursive lock lock
The only difference with the Lock: an R lock in the same thread can execute acquire a few times but the execution should acquire the corresponding release several times if a thread
Has been performed acquire, acquire other threads will not be executed
from threading import RLock, Lock, Thread # l = Lock() # # l.acquire() # print("1") # l.acquire() # print("2") l = RLock() # l.acquire() # print("1") # l.acquire() # print("2") def task(): l.acquire() print("子run......") l.release() # 主线程锁了一次 l.acquire() l.acquire() l.release() l.release() t1 = Thread(target=task) t1.start()
"" " Semaphore to know Lock RLock can now be locked while the code may be how many threads concurrently access lock Lock a toilet at the same time only one Semaphore to lock a public toilet at the same time can be a bunch of people use: Only for concurrency control access concurrent modification does not prevent problems caused by "" " from Threading Import Semaphore, the Thread Import Time S = Semaphore (. 5) DEF Task (): s.acquire () Print (" sub-RUN ") the time.sleep (. 3) Print ( "sub-over") s.release () for I in Range (10): T = the Thread (target = Task) t.start ()