This section briefly describes how to create and lock Python threads and how to use python threads.

Source: Internet
Author: User
Tags sleep function

This section briefly describes how to create and lock Python threads and how to use python threads.

Create thread
There are two ways to create a thread:
1. directly call threading. Thread to construct the thread object. The Thread parameters are as follows:
Class threading. Thread (group = None, target = None, name = None, args = (), kwargs = {})
Group is None;
Target is the function to be executed by the thread;
Name is the name of the thread. You can also call setName () to set it after the object is constructed;
Args is a tuple type parameter, which can be multiple. If only one parameter can be input in the tuple format, for example (1 ,);
Kwargs is a dict-type parameter, that is, a named parameter.
Other methods of threading. Thread object:
Start (), used to start the thread;
Join (), wait until the thread ends;
IsAlive () to get the thread status

SetDeamon (): Set the thread to deamon. It must be called before start (). The default value is demon.
Note: The main python thread exits when no non-deamon thread exists.

Threading. currentthread (), used to obtain the current thread;
Threading. enumerate (), used by all the threads currently alive;

# Coding: utf-8import threadingdef func1 (num): for I in range (num): # threading. currentThread () gets the current thread, getName () gets the thread name print 'I am % s. num: % s' % (threading. currentThread (). getName (), I) def main (thread_num): thread_list = [] # define a thread list for I in range (thread_num): thread_list.append (threading. thread (target = func1, args = (3,) for a in thread_list: #. setDaemon (True): the default value of setDaemon is False. It is a non-daemon. # It indicates that after the main thread and other sub-threads are completed, at the end # if it is set to True, it indicates that a daemon thread sub-thread will end with the end of the main thread # I heard that the heartbeat thread generated by the service monitoring tool is the daemon thread. start () for a in thread_list:. join () # indicates waiting until the thread has finished running main (3)

Running result

I am Thread-1.num:0I am Thread-1.num:1I am Thread-1.num:2I am Thread-2.num:0I am Thread-2.num:1I am Thread-2.num:2I am Thread-3.num:0I am Thread-3.num:1I am Thread-3.num:2

2. inherit from threading. Thread directly, and then rewrite the _ init _ method and run method.

# Coding: utf-8import threadingclass MyThread (threading. thread): # inherit from the parent class threading. thread def _ init _ (self, num): threading. thread. _ init _ (self) self. num = num # write the code to be executed to the run function. After creation, the thread will directly run the run function def run (self): for I in range (self. num): print 'I am % s. num: % s' % (self. getName (), I) for I in range (3): t = MyThread (3) t. start () t. join ()

Running result

I am Thread-1.num:0I am Thread-1.num:1I am Thread-1.num:2I am Thread-2.num:0I am Thread-2.num:1I am Thread-2.num:2I am Thread-3.num:0I am Thread-3.num:1I am Thread-3.num:2


Lock usage
Suppose we have a public data x (also known as shared resources and critical resources), and then run 10 threads to access this variable and modify it, then unexpected results are obtained.

Import threading # import threading module import time # import time module class mythread (threading. thread): # create a class def _ init _ (self, threadname) through inheritance: # initialization method # Call the initialization method threading of the parent class. thread. _ init _ (self, name = threadname) def run (self): # overload the run method global x # Use global to indicate that x is the global variable for I in range (3 ): x = x + 1 time. sleep (2) # Call the sleep function to sleep the thread for 5 seconds print x tl = [] # define the list for I in range (10): t = mythread (str (I )) # class instantiation tl. append (t) # Add the Class Object to the list x = 0 # assign x to 0for I in tl: I. start () # Run threads in sequence


Running result

[root@localhost ~]# python syn.py
30303030303030303030

Since x is a global variable (shared resource), every thread will sleep after performing operations on x.
When the thread is sleeping, other threads also start to execute operations,
After five seconds of sleep, the value of x is changed to 30.

Use mutex to protect public resources. A mutex lock is used to ensure that only one thread accesses public resources at a time point for simple synchronization.
Mutex Lock: threading. Lock
Mutex lock method: acquire () get lock release (): release lock
After a lock is obtained by a thread, the lock enters the locke state (locked). When other threads attempt to obtain the lock, the lock changes to the synchronous blocking state,
When the thread that owns the thread lock calls the lock method release (), the lock will be released, and the lock will become the unlocked state, then select a thread in the synchronization blocking status to obtain the lock.

Import threading # import threading module import time # import time module class mythread (threading. thread): # Use inheritance to create the class def _ init _ (self, threadname): # initialization method threading. thread. _ init _ (self, name = threadname) def run (self): # overload the run method global x # Use global to indicate that x is the global variable lock. acquire () # Call lock's acquire Method for I in range (3): x = x + 1 time. sleep (2) # Call the sleep function to sleep the thread for five seconds print x lock. release () # Call lock's release method lock = threading. lock () # class instantiation tl = [] # definition list for I in range (10): t = mythread (str (I) # class instantiation tl. append (t) # Add the Class Object to the list x = 0 # assign x to 0for I in tl: I. start () # Run threads in sequence


Running result:

[root@localhost ~]# python syn.py
36912151821242730

Reentrant lock: threading. RLock ()
The method is the same as the mutex lock.
Assume that a lock is nested: There is a thread that gets the lock and shares the resource, but another lock is required to get another resource, you just need to put the following in the Code:

lock = threading.Lock()

To:

lock = threading.RLock()

Articles you may be interested in:
  • Python multi-thread programming (6): reentrant lock RLock
  • Python multi-thread programming (5): deadlock Formation
  • Python multi-thread programming (4): Use Lock mutex Lock
  • Analysis on multithreading and program lock in Python
  • Python multi-thread threading. Lock usage example
  • Python thread learning example
  • Python implements simple multi-thread task queue
  • Comparison of Python multi-thread image capturing efficiency
  • Python multi-thread, asynchronous, and multi-process crawler implementation code
  • Using Queue and Condition for Thread Synchronization in Python

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.