Python learning-Python threads, learning python threads

Source: Internet
Author: User
Tags thread stop

Python learning-Python threads, learning python threads

I. Thread Creation

1 # Method 1: The method to be executed is passed as the parameter to the Thread constructor 2 import threading 3 import time 4 5 def show (arg): 6 time. sleep (2) 7 print ('thread' + str (arg) 8 9 for I in range (10): 10 t = threading. thread (target = show, args = (I,) 11 time. sleep (2) 12 t. start () 13 14 # Method 2: Inherit from Thread and override run () 15 class MyThread (threading. thread): 16 def _ init _ (self, num): 17 threading. thread. _ init _ (self) 18 self. num = num19 20 def run (self): # define the function 21 print ("running on number: % s" % self. num) 22 time. sleep (3) 23 24 25 if _ name _ = '_ main _': 26 t1 = MyThread (1) 27 t2 = MyThread (2) 28 t1.start () 29 time. sleep (3) 30 t2.start ()

Note:
Thread (group = None, target = None, name = None, args = (), kwargs = {})
Group: thread group, which has not been implemented yet. When the database is referenced, the prompt must be None.
Target: method to be executed
Name: thread name
Args/kwargs: the parameter of the method to be passed in. The two parameters args and kwargs are actually two choices.
# Instance method
IsAlive (): whether the returned thread is running
Get/setName (name): get/set the thread name
Is/setDaemon (bool): gets/sets whether to guard the thread. The initial value is inherited from the thread where the thread is created. When no non-daemon thread is still running, the program will terminate.
Start (): start the thread
Join ([timeout]): the thread that blocks the current context.

Ii. multi-thread usage in Python

1 import threading 2 from time import ctime, sleep 3 4 def music (func): 5 for I in range (2): 6 print ("I was listening to % s. % s "% (func, ctime () 7 sleep (1) 8 def move (func): 9 for I in range (2 ): 10 print ("I was at the % s! % S "% (func, ctime () 11 sleep (5) 12 13 threads = [] 14 t1 = threading. thread (target = music, args = ('fairy tale town',) 15 threads. append (t1) 16 t2 = threading. thread (target = move, args = ('Transformers ',) 17 threads. append (t2) 18 19 if _ name _ = '_ main _': 20 for t in threads: 21 t. setDaemon (True) 22 t. start () 23 24 print ("all over % s" % ctime ())

Note:

Threads = []

T1 = threading. Thread (target = music, args = ('fairy tale town ',))

Threads. append (t1)

The threads array is created, Thread t1 is created, and the threading. Thread () method is used. In this method, the music method target = music is called, and The args method is used to transmit parameters to music. Install the created thread t1 in the threads array.

Then, create thread t2 in the same way and load the t2 to the threads array.

For t in threads:

T. setDaemon (True)

T. start ()

Finally, the array is traversed through the for loop. (The array is loaded with t1 and t2 threads)

SetDaemon ()

SetDaemon (True) declares a thread as a daemon. It must be set before the start () method is called. If it is not set as a daemon, the program will be suspended infinitely. After the sub-thread starts, the parent thread continues to execute. After the parent thread finishes executing the last statement print "all over % s" % ctime (), it does not wait for the sub-thread, the sub-thread is also terminated.

SerDeamon (False) (default) Foreground thread. During the main thread execution, the foreground thread is also in progress. After the main thread completes execution, the main thread stops after the foreground thread completes execution.

Running result:

I was listening to fairy tale town. Thu Jun 22 23:23:07 when I was at the Transformers! Thu Jun 22 23:23:07 upload all over Thu Jun 22 23:23:07 2017

According to the execution results, both the Sub-thread (muisc, move) and the main thread (print "all over % s" % ctime () start at the same time, however, since the execution of the main thread ends, the sub-thread is terminated.

Adjustment procedure:

 

1 if __name__ == '__main__':2     for t in threads:3         t.setDaemon(True)4         t.start()5     6     t.join()7 8     print "all over %s" %ctime()

The join () method is added to wait for the thread to terminate. The function of join () is that the parent thread of this subthread will be blocked until the subthread completes running.

The join () method is located outside the for loop. That is to say, the main process must be executed only after the two processes in the for loop are completed.

Running result:

1 ############ running result ################### 2 I was listening to fairy tale town. thu Jun 22 23:34:22 20173 I was at the Transformers! Thu Jun 22 23:34:22 20174 I was listening to fairy tale town. Thu Jun 22 23:34:23 20175 I was at the Transformers! Thu Jun 22 23:34:27 20176 all over Thu Jun 22 23:34:32 2017

From the result, we can see that each song waits for 1 second, and the movie waits for 5 seconds, but is synchronized. The total time is 5 seconds.

Iii. thread LOCK (LOCK, RLOCK)
Since threads are randomly scheduled and each thread may only execute n executions, dirty data may occur when multiple threads modify the same data at the same time, A thread lock occurs-a thread is allowed to perform operations at the same time.

The Lock is the lowest available synchronous command. When the Lock is locked, it is not owned by a specific thread. Lock includes two states: Locked and unlocked, and two basic methods.

It can be considered that the Lock has a Lock pool. When the thread requests the Lock, it moves the thread into the pool until it gets the Lock and leaves the pool. The threads in the pool are in the synchronization blocking status in the status chart.

RLock (reentrant lock) is a synchronous command that can be requested multiple times by the same thread. RLock uses the concepts of "owned Threads" and "recursive level". When it is locked, RLock is owned by a thread. Threads with RLock can call acquire () again. The release () must be called for the same number of times when the lock is released.

It can be considered that RLock contains a lock pool and a counter whose initial value is 0. Each time acquire ()/release () is successfully called, the counter will be + 1/-1, when the value is 0, the lock is not locked.

  In short, Lock is global, and Rlock is a thread.

1. No lock is used.

 1 import threading 2 import time 3  4 num = 0 5  6 def show(arg): 7     global num 8     time.sleep(1) 9     num +=110     print(num)11 12 for i in range(10):13     t = threading.Thread(target=show, args=(i,))14     t.start()15 16 print('main thread stop')

Multiple operations may cause confusion. This scenario is suitable for the use of locks.

2. Use locks

1 import threading 2 import time 3 4 num = 0 5 lock = threading. RLock () 6 7 # When acquire ([timeout]) is called, the thread will remain blocked, 8 # Until the lock is obtained or after the timeout seconds (optional ). 9 # Return whether to obtain the lock. 10 def show (arg): 11 lock. acquire () 12 global num13 time. sleep (1) 14 num + = 115 print (num) 16 lock. release () 17 18 for I in range (10): 19 t = threading. thread (target = show, args = (I,) 20 t. start () 21 22 print ('main thread stop ')

The number will be printed step by step after the lock is added, so it will not be messy due to congestion!


4. Semaphore)

The mutex lock allows only one thread to change data at the same time, while Semaphore allows a certain number of threads to change data at the same time. For example, if there are three pits in the toilet, only three persons can go to the toilet at most, the people later can only wait for someone to come in.

1 import threading, time 2 3 def run (n): 4 semaphore. acquire () 5 time. sleep (3) 6 print ("run the thread: % s" % n) 7 semaphore. release () 8 9 if _ name _ = '_ main _': 10 num = 011 semaphore = threading. boundedSemaphore (5) # Up to five threads can run at the same time 12 for I in range (20): 13 t = threading. thread (target = run, args = (I,) 14 t. start ()

5. Events)

The Python thread events are mainly used by the main thread to control the execution of other threads. The events mainly provide three methods: set, wait, and clear.

Event processing mechanism: a global "Flag" is defined. If the "Flag" value is False, when the program executes the event. the wait method is blocked. If the "Flag" value is True, the event. the wait method is no longer blocked.

Clear: Set "Flag" to False

Set: set "Flag" to True

Use threading. Event to implement inter-thread Communication

Threading. Event enables a thread to wait for notifications from other threads and pass the Event to the thread object. By default, the Event has a built-in flag with the initial value of False.
Once the thread enters the waiting state through the wait () method, until another thread calls the set () method of the Event to set the built-in flag to True,
This Event will notify all threads in the waiting state to resume running.

1 import threading 2 3 def do (event): 4 print ('start') 5 event. wait () 6 print ('end') 7 8 event_obj = threading. event () 9 10 for I in range (10): 11 t = threading. thread (target = do, args = (event_obj,) 12 t. start () 13 14 event_obj.clear () # continue to block 15 16 PLD = input ('input: ') 17 if PLD = 'true': 18 event_obj.set () # Wake up

Condition)
The so-called condition variable, that is, this mechanism can be used by the thread to access relevant data only after a specific condition is met!

It uses the Condition class, because it can also be used as the lock mechanism, so it also has the acquire method and the release method, and it also has the wait, policy, policyall method.

A simple production consumer model controls the increase or decrease of the number of products by using conditional variables. One call of the producer product is + 1, and one call of the consumer product is-1. The Condition class can be used as well as the lock mechanism, so it also has the acquire method and the release method, and it also has Wait, policy, and policyall methods.
1 import threading 2 import time 3 4 # product class 5 class Goods: 6 def _ init _ (self): 7 self. count = 0 8 9 def add (self, num = 1): 10 self. count + = num11 12 def sub (self): 13 if self. count> = 0: 14 self. count-= 115 16 def empty (self): 17 return self. count <= 018 19 # Producer 20 class Producer (threading. thread): 21 def _ init _ (self, condition, goods, sleeptime = 1): 22 threading. thread. _ init _ (self) 23 self. cond = condition24 self. goods = goods25 self. sleeptime = sleeptime26 27 def run (self): 28 cond = self. cond29 goods = self. goods30 while True: 31 # Lock resource 32 cond. acquire () 33 goods. add () 34 print ("product quantity:", goods. count, "producer thread") 35 # Wake up all the waiting threads-> actually, it is to wake up the consumer process 36 cond. policyall () 37 # unlock resource 38 cond. release () 39 time. sleep (self. sleeptime) 40 41 42 # Consumer 43 class Consumer (threading. thread): 44 def _ init _ (self, condition, goods, sleeptime = 2): 45 threading. thread. _ init _ (self) 46 self. cond = condition47 self. goods = goods48 self. sleeptime = sleeptime49 50 def run (self): 51 cond = self. cond52 goods = self. goods53 54 while True: 55 time. sleep (self. sleeptime) 56 # Lock resource 57 cond. acquire () 58 # if there is no product, let the thread wait 59 while goods. empty (): 60 cond. wait () 61 goods. sub () 62 print ("product quantity:", goods. count, "Consumer thread") 63 64 65g = Goods () 66 c = threading. condition () 67 pro = Producer (c, g) 68 pro. start () 69 con = Consumer (c, g) 70 con. start ()

7. Timer)

 1 import threading 2 def SayHello(): 3     print("hello world!") 4     t=threading.Timer(3,SayHello) 5     t.start() 6 def other_func(): 7     print("let me running!") 8     t=threading.Timer(1,other_func) 9     t.start()10 11 if __name__ == "__main__":12     SayHello()13     other_func()

 

 

 

 

 

 

 

 

 

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.