In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
How to understand Thread in Python thread programming? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible method.
Thread programming (Thread) 1. Basic Thread Concepts 1.1.What Thread
Threads are called lightweight processes
Threads can also use computer multi-core resources, which is a way of multitasking programming.
Thread is the smallest unit in which the system allocates the kernel
A thread can be understood as a branch task of a process.
1.2. Thread characteristics
A process can contain multiple threads
A thread is also a running behavior that consumes computer resources.
All threads in a thread share the resources of this process
The operation of multiple threads does not affect each other.
Thread creation and destruction consume far less resources than processes.
Each thread also has its own ID and other characteristics.
Second, threading module to create thread 1, create thread object from threading import Threadt = Thread () function: create thread object parameters: target binding thread function args tuple to thread function location parameter kwargs dictionary to thread function key value parameter 2, start thread t.start () 3, reclaim thread t.join ([timeout]) 4, code demonstration "thread1.py thread basic use steps: 1. Encapsulate thread function 2. Create thread object 3. Start thread 4. Recycling thread "" import osfrom threading import Threadfrom time import sleepa = thread function def music (): for i in range (3): sleep (2) print ('play: yellow River chorus% s'% os.getpid ()) global a print ("a," A) a = 100thread creation thread object t = Thread (target=music) # start thread t.start () for i in range (3): sleep (1) print ('play: beauty love% s'% os.getpid ()) # Recycle thread t.join () print ('program ends') print ("a,", a) 5, thread object properties
1.t.name thread name
2.t.setName () sets the thread name
3.t.getName () gets the thread name
4.t.is_alive () to see if the thread is in the lifecycle
5.t.daemon sets main thread and branch thread exit branch thread also exit. To set up before start, it is not usually used with join
6. Code demonstration
From threading import Threadfrom time import sleepdef fun (): sleep (3) print ('thread property test') t = Thread (target=fun, name='ceshi') # the main thread exits the branch thread must also exit before the start is meaningless t.setDaemon (True) t.start () print (t.getName ()) t.setName ('Tedu') print (' is alive:') T.is_alive () print ('daemon', t.daemon) 6, custom thread class
1. Creation step
1. Inherit the Thread class
two。 Override the _ _ init__ method to add your own properties and use super to load parent class properties
3. Override the run method
two。 Usage
1. Instantiate object
two。 Start automatically executes run method
3. Call join recovery thread
Code demonstration
"" Custom thread class example "" from threading import Thread# custom thread class class ThreadClass (Thread): # override parent class init def _ _ init__ (self, * args) * * kwargs): self.attr = args [0] # load parent class init super (). _ _ init__ () # suppose you need many steps to complete the function def F1 (self): print ('1') def f2 (self): print (2) # rewrite run logical maid def run (self): self.f1 ( ) self.f2 () t = ThreadClass () t.start () t.join () 7, A very important exercise. I don't know a lot about from threading import Threadfrom time import sleep. Ctimeclass MyThread (Thread): def _ init__ (self, group=None, target=None, name=None, args= (), kwargs=None, *, daemon=None): super (). _ init__ () self.fun = target self.args = args self.kwargs = kwargs def run (self): self.fun (* self.args, * * self.kwargs) def player (sec) Song): for i in range (3): print ("Playing% s:% s"% (song, ctime ()) sleep (sec) t = MyThread (target=player, args= (3,), kwargs= {'song':' quantity'}) t.start () t.join () 8, inter-thread communication
1. Communication method
1. Communication between threads using global traversal
two。 Scramble for shared resources
1. Shared resources: a resource that can be operated by multiple processes or threads is called a shared resource, and a code segment that operates on a shared resource is called a critical section.
two。 Impact: disordered operations on public resources may lead to data confusion or operational errors. At this time, it is often necessary to coordinate the operation sequence by synchronous mutual exclusion mechanism.
3. Synchronous mutual exclusion mechanism
1. Synchronization: synchronization is a collaborative relationship in which multiple processes or threads form a coordination to complete the operation and perform the operation in an orderly manner according to the necessary steps.
two。 Mutex: mutual exclusion is a constraint. When a process or thread owns a resource, it will be locked, and other process threads will not be able to operate the resource until it is unlocked.
# # 9. Thread synchronization mutex method 1. Thread Event code demonstrates from threading import Event# creation thread event object e = Event () # blocking waits e to be set by sete.wait ([timeout]) # to make wait end blocking e.set () # return e to unset state e.clear () # check whether current e is set e.is_set () "" event thread mutual exclusion method demonstration "from threading import Event" Threads = None # for communication e = Event () def yzr (): print ('Yang Zirong comes to worship the mountain') global s s = 'Heavenly King covering the Earth Tiger' e.set () # after operating the shared resources, set t = Thread (target=yzr) t.start () print ('say the password is one of your own') e.wait () # blocking and waiting for e.set () if s = = 'Heavenly King covering the Earth Tiger': Print ('Baota town river demon') print ('confirmed the look in the eyes You are the right person') e.clear () else: print ('shoot him...') t.join () print ('end of the program') 2. Thread lock Lock code demonstration from threading import Locklock = Lock () create lock object lock.acquire () lock if lock is already locked and then called will block lock.release () unlock with lock: lock. With code block unlock automatically unlock "" thread_lock thread lock demonstration "" from threading import Thread " Locka = b = 0lock = Lock () def value (): while True: # Lock lock.acquire () print ('averse% ddirection baked% d'% (a) B) if a! = b else print ('an is not equal to b') # unlock lock.release () t = Thread (target=value) t.start () while True: # with start locking with lock: a + = 1 b + = 1 # with unlock automatically t.join () print ('program end') 10, deadlock and its handling 1. Define
Deadlock refers to a blocking phenomenon caused by competition for resources or communication between two or more threads during execution. If there is no external force, they will not be able to push forward. At this point, it is said that the system is in a deadlock state or that the system has a deadlock.
two。 Graphic illustration
3. Deadlock generation condition
Necessary conditions for deadlock occurrence
Mutex condition: refers to the exclusive use of allocated resources by a thread, that is, a resource is occupied by only one process for a period of time. If there are other processes requesting resources at this time, the requestor can only wait until the process in possession of the resource is released.
Request and retention condition: refers to that the thread has maintained at least one resource, but has made a new resource request, and the resource has been occupied by other processes, and the requesting thread blocks, but holds on to the other resources it has acquired.
No deprivation condition: refers to the resources obtained by the thread, which cannot be deprived before it is used up, but can only be released by itself at the end of use. Usually, CPU memory resources can be forcibly provisioned by the system.
Loop waiting condition: when a deadlock occurs, there must be a circular chain of thread-resources, that is, T0 in the process set {T0, T1, T2, Tn} is waiting for a resource occupied by T1; T1 is waiting for the resource occupied by T2,. Tn is waiting for resources that have been occupied by T0.
The cause of deadlock
To put it simply, the cause of deadlock can be summed up in three sentences:
The current thread has resources that other threads need
The current thread waits for resources already owned by other threads
Don't give up the resources they have.
How to avoid deadlock
Deadlock is a phenomenon that we do not want to see, and we should avoid deadlock as much as possible. Deadlocks are prevented by setting certain restrictions to break one or more of the four necessary conditions for deadlocks. Deadlock prevention is an easy method to achieve. However, the restrictions imposed are often too strict, which may lead to the utilization of system resources.
4. Deadlock code demonstration from time import sleepfrom threading import Thread, Lock# transaction class class Account: def _ _ init__ (self, _ id, balance, lock): # user self._id = _ id # Deposit self.balance = balance # Lock self.lock = lock # withdrawal def withdraw (self Amount): self.balance-= amount # savings def deposit (self, amount): self.balance + = amount # balance def get_balance (self): return self.balanceTom = Account ('Tom', 5000, Lock ()) Alex = Account (' Alex', 8000, Lock ()) def transfer (from_, to Amount): # Lock your account if from_.lock.acquire (): # account reduction from_.withdraw (amount) sleep (0.5) if to.lock.acquire (): to.deposit (amount) to.lock.release () from_.lock.release () print ('transfer completed% s to% S transfer% d'% (from_._id To._id, amount) # transfer (Tom, Alex, 1000) T1 = Thread (target=transfer, args= (Tom, Alex, 2000)) T2 = Thread (target=transfer, args= (Alex, Tom, 3500) t1.start () t2.start () t1.join () t2.join () print ('Program ends') GIL problem of python thread GIL1.python thread (global interpreter lock)
What is GIL: because the interpreter lock is added to the python interpreter design, the python interpreter can only interpret and execute one thread at a time, which greatly reduces the execution efficiency of the thread.
The consequence: because the thread will actively give up the interpreter to interpret other threads when it encounters blocking. Therefore, python multithreading can improve the program efficiency when executing multi-blocking and high-latency IO, but not in other cases.
Suggestions on GIL problem
Try to use processes to achieve non-blocking concurrency
Do not use c as the interpreter (Java C #)
In the non-blocking state, the execution efficiency of multithreaded programs is almost the same as that of single-threaded programs, or even lower than that of single-threaded programs. However, multiple processes running the same content can significantly improve efficiency.
This is the answer to the question about how to understand Thread in Python thread programming. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.