Python Threading Thread and Mutex and Deadlock and GIL Lock
- 2021-07-24 11:16:31
- OfStack
Import thread package
import threading
Prepare function thread and pass parameters
t1 = threading.Thread(target=func,args=(args,))
Class inherits threads and creates thread objects
class MyThread(threading.Thread)
def run(self):
pass
if __name__ == "__main__":
t = MyThread()
t.start()
Threads share comprehensive variables, but data errors occur when sharing global variables
Using the Lock class in the threading module, adding mutex can solve the problem of threads sharing global variables
# Create a lock
mutex = threading.Lock()
# Lock
mutex.acquire()
# Release lock
mutex.release()
Mutex may cause deadlock problems
When multiple resources are shared between threads, if two threads occupy one part of the resources respectively and wait for each other's resources at the same time, deadlock will be caused.
Solution:
1. Banker algorithm: When designing the program, think about the spatio-temporal relationship between locking and releasing
2. Add a timeout wait
Multithreaded GIL Global Interpreter Lock in Python
GIL is a legacy of the C language version of the python interpreter
The GIL lock makes only one thread running at the same time in python
However, multithreading is still faster than closing a single thread after all, because other threads can run during the time period when one thread IO is blocked
GIL lock and Mutex lock are different, GIL lock is to lock thread, Mutex lock is to lock thread transaction, Mutex lock is written by the developer himself, GIL lock source and python interpreter of C version
Solution to GIL
1. Using the java version of the python interpreter
2. Complete this section using a different language code
Summarize
The above is this site to introduce you Python Threading thread/Mutex/Deadlock/GIL lock, I hope to help you, if you have any questions welcome to leave me a message, this site will reply to you in time!