In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-23 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
Web development thread is what, many novices are not very clear about this, in order to help you solve this problem, the following small series will be explained in detail for everyone, there are people who need this can learn, I hope you can gain something.
The central processor's scheduling unit, simply put, is the end executor in the program, which is equivalent to the position of the younger brother.
Some people say that Python thread is a chicken rib, this is because of GIL, but not blindly chicken rib, after all, in the execution of io operations or quite useful, but in the execution of calculations is unsatisfactory. Let's look at the specific use of threads:
1. Import thread module:
import threading as t
2. Usage of threads
tt=t.Thread(group=None,target=None,name=None,args=(),kwargs={},name='',daemon=None) group: thread group, must be None target: function running args: parameter tuple of passed function kwargs: parameter dictionary of passed function name: thread name daemon: Whether the thread exits with the main thread (daemon thread) The return value of the Thread method also has the following methods: tt.start() : activate the thread, tt.getName () : get the name of the thread tt.setName (): set the name of the thread tt.name: Gets or sets the name of the thread tt.is_alive(): Determine whether the thread is active tt.isAlive(): Determine whether the thread is active tt.setDaemon() Set it as a daemon thread (Default: False) tt. isDaemon(): Determine whether it is a daemon thread tt.ident: Get the identifier of the thread. tt.join(): Executes each thread one by one, then proceeds tt.run (): Automatically executes threads Methods of object t also include: t.active_count(): Returns the number of running threads t.enumerate(): Returns a list of running threads t.current_thread().getName() Gets the name of the current thread t.TIMEOUT_MAX Sets the global timeout for t
Let's take a look below:
3. create threads
Threads can be created using the Thread method, or you can override the thread class's run method implementation. Threads can be single-threaded or multi-threaded.
Use the Thread method to create:
1. single-threaded
def xc(): for y in range(100): print ('Running '+str(y)) tt=t.Thread(target=xc,args=()) #method joins thread tt.start() #starts thread tt.join() #waits for child thread to end
2. multithreading
def xc(num): print ('run line:'+ str(num)) c=[] for y in range(100): tt=t.Thread(target=xc,args=(y,)) tt.start() #Start thread c.append(tt) #Create a list and add threads for x in c: x.join() #Wait for the child thread to end II. Overwrite the class method of the thread
1. single-threaded
class Xc(t.Thread): #Inherit Thread class def __init__(self): super(Xc, self).__ init__() def run(self): #Overwrite the run method for y in range(100): print ('Running '+str(y)) x=Xc() x.start() #Start thread x.join() #Wait for child thread to end You can also write: Xc().run() The effect is the same as above
2. multithreading
class Xc(t.Thread): #Inherit Thread class def __init__(self): super(Xc, self).__ init__() def run(self,num): #override run method print ('run line:'+ str(num)) x=Xc() for y in range(10): x.run #Run
4. thread lock
Why lock it up, you'll see:
Multi-thread access to an object at runtime will preempt resources, so we have to tie it down, so we have to give him a lock to lock him, which is synchronous lock. To unlock it, we first have to create locks, and there are two types of locks in threads: Lock and RLock.
1) Lock
How to use:
#Acquire lock When the lock is not acquired, the default enters the blocking state, and the timeout time is set until the lock is acquired. Timeout is disabled when not blocking. Returns False if the lock is still not acquired after timeout. Lock.acquire(blocking=True,timeout=1) #Release lock, locked lock, will be set to unlocked. If the call is unlocked, a RuntimeError exception is thrown. Lock.release()
Mutex lock, synchronous data, solve multithreaded security problems:
n=10 lock=t.Lock() def xc(num): lock.acquire() print ('Run +:'+ str(num+n)) print ('Run-:'+ str(num-n)) lock.release() c=[] for y in range(10): tt=t.Thread(target=xc,args=(y,)) tt.start() c.append(tt) for x in c: x.join()
This is organized, and the output is also + first and then-. Lock Using the same resource multiple times in a thread can cause deadlocks.
Deadlock problem:
n=10 lock1=t.Lock() lock2=t.Lock() def xc(num): lock1.acquire() print ('Run +:'+ str(num+n)) lock2.acquire() print ('Run-:'+ str(num-n)) lock2.release() lock1.release() c=[] for y in range(10): tt=t.Thread(target=xc,args=(y,)) tt.start() c.append(tt) for x in c: x.join() II. RLock
It can be recursive compared to Lock, supports multiple requests for the same resource in the same thread, and allows multiple locks in the same thread, but acquire and release must appear in pairs.
Using Recursive Locks to Resolve Deadlocks:
n=10 lock1=t.RLock() lock2=t.RLock() def xc(num): lock1.acquire() print ('Run +:'+ str(num+n)) lock2.acquire() print ('Run-:'+ str(num-n)) lock2.release() lock1.release() c=[] for y in range(10): tt=t.Thread(target=xc,args=(y,)) tt.start() c.append(tt) for x in c: x.join()
At this point, the output variable becomes just a bar, no longer arbitrarily preempt resources. For thread locks, you can also use with more conveniently:
#with context management, lock objects support context management with lock: #with means automatically open automatic release lock for i in range(10): #No one else is allowed to work while locked print(i) #above and below are equivalent if lock.acquire(1):#lock successfully continue to work, do not lock successfully wait, 1 stands for exclusive for i in range(10): #Other threads cannot work during lock print(i) lock.release() #Release lock III. Conditional lock
Wait for pass, Condition(lock=None), can be passed lock or Rlock, default Rlock, use method:
Condition.acquire(*args) Condition.wait(timeout=None) to wait for notification, timeout to set timeout Condition.notify(num) to wake up at most a specified number of waiting threads, no waiting threads have no action Condition.notify_all() to wake up all waiting threads or notifyAll()def ww(c): with c: print('init') c.wait(timeout=5) #Set wait timeout 5 print('end') def xx(c): with c: print('nono') c.notifyAll() #Wake up all threads print('start') c.notify(1) #Wake up a thread print('21') c=t.Condition() #Create condition t.Thread(target=ww,args=(c,)).start() t.Thread(target=xx,args=(c,)).start()
This allows you to wake up other threads existing in other functions while waiting.
5. semaphore
Semaphores can be divided into bounded semaphores and unsolved semaphores. Let's take a look at their usage in detail below:
1. bounded semaphore
It does not allow release to be used outside the initial value range, otherwise it throws a ValueError exception.
#Construction methods. value is the initial semaphore. value is less than 0, ValueError exception is thrown b=t.BoundedSemaphore(value=1) #When a semaphore is acquired, the counter is decremented by 1, i.e. the value of_value is decremented by 1. If the value of_value is 0, it becomes blocked. Acquire Success Returns True BoundedSemaphore.acquire(blocking=True,timeout=None) #Release semaphore, increment counter by 1. That is, the value of_value is increased by 1. Exceeding the initial value will throw an exception ValueError. BoundedSemaphore.release() #semaphore, current semaphore BoundedSemaphore._ value
You can see that there is an error after the release.
II. Unbounded semaphore
It does not check the upper limit of release, just a simple up and down counter.
You can see that although there is an extra release, there is no problem, and the number of semaphores is not limited.
6.Event
Inter-thread communication, through the thread set signal flag (flag) False or True to operate, common methods are:
event.set() flag set to True event.clear() flag set to False event.is_set() flag whether True, if event.isSet()==False will block the thread; set the length of time to wait for flag to True, None is infinite wait. Wait until it returns True, wait until timeout returns False event.wait(timeout=None)
Here is an example:
import time e=t.Event() def ff(num): while True: if num=5: e.wait(timeout=1) #Wait for signal flag is true e.set() print ('Start ') if e.isSet(): #Clear flag if signal flag is true e.clear() print ('Stop ') if num==10: e.wait(timeout=3) e.clear() print ('exit ') break num+=1 time.sleep(2) ff(1)
After setting the delay, you can see that the effect is quite obvious. He will do whatever we ask him to do.
7.local
It is possible to create variables that are entirely their own for each thread (thread-local variables), and their values exist as dictionaries in the thread that is currently calling it. Let's take a look below:
l=t.local() #Create a thread-local variable def ff(num): l.x=100 #Set the value of x method of l variable to 100 for y in range(num): l.x+=3 #Change value print(str(l.x)) for y in range(10): t.Thread(target=ff,args=(y,)).start() #Start thread execution
So, can we make the x method of a variable global? Let's take a look:
We can see that he is wrong, and the reason for this error is that there is no attribute x in this class. We can simply understand that local variables only accept local variables.
8.Timer
Set up a timing schedule to repeatedly execute a method within a specified time. His method of use is:
t.Timer(num,func,*args,**kwargs) #Restart the program again within the specified time
Let's take a look below:
def f(): print('start') global t #prevents thread pile-ups from causing final program exit tt= t.Timer(3, f) tt.start() f()
This achieves the effect of executing the f function every three seconds.
Did reading the above help you? If you still want to have further understanding of related knowledge or read more related articles, please pay attention to the industry information channel, thank you for your support.
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.