"" "In Python, there are two ways to use threads: a function or a class to wrap a thread object.
1. Function: Call the Start_new_thread () function in the thread module to generate a new thread. The end of the thread can wait for the thread to end naturally, or you can call the Thread.exit () or Thread.exit_thread () method in the inline function.
Import time
Import Thread
def test ():
Thread.start_new_thread (timer, ())
Thread.start_new_thread (Timer, (2,2))
If __name__== ' __main__ ':
print ' Thread starting '
Test ()
Time.sleep (20)
Thread.exit_thread ()
print ' Exit ... '
2, create threading. A subclass of thread to wrap a thread object,
Threading. Use of the thread class:
1, call threading in the __init__ of your own thread class. Thread.__init__ (self, name = ThreadName)
ThreadName is the name of the thread
2, run (), usually requires rewriting, writing code to implement the required functionality.
3,getname (), get the Thread object name
4,setname (), setting the thread object name
5,start (), starting thread
6,jion ([timeout]), waiting for another thread to finish before running.
7,setdaemon (BOOL), which sets whether the child thread ends with the main thread, must be called before start (). The default is False.
8,isdaemon () to determine whether the thread is terminated with the main threads.
9,isalive () to check if the thread is running.
Import threading
Import time
If __name__== ' __main__ ':
Test ()
"""
"""
The problem arises because there is no control over the access of multiple threads to the same resource, causing damage to the data and making the results of the thread run unpredictable. This behavior is called "Thread insecurity."
Import threading
Import time
Class MyThread (threading. Thread):
def run (self):
For I in range (3):
Time.sleep (1)
msg= ' I am ' + self.getname () + ' @ ' +str (i)
Print msg
def test ():
For I in range (5):
T=mythread ()
T.start ()
If __name__== ' __main__ ':
Test ()
The above example leads to the most common problem with multithreaded programming: Data sharing. Synchronization control is required when multiple threads modify a shared data.
Thread synchronization ensures that multiple threads secure access to competing resources, and the simplest synchronization mechanism is to introduce mutexes. A mutex introduces a state to a resource: locked/non-locked. When a thread changes the shared data, it locks it, the state of the resource is locked, the other thread cannot be changed, and until the thread frees the resource, the state of the resource becomes "non-locked", and the other thread can lock the resource again. The mutex ensures that only one thread is written at a time, thus guaranteeing the correctness of the data in multi-threaded situations. Where the lock method acquire can have a time-out optional parameter of timeout. If timeout is set, the return value after timeout can be used to determine if a lock has been obtained, allowing for some additional processing
The lock class is defined in the threading module
Import threading
Import time
Class MyThread (threading. Thread):
def run (self):
Global num
Time.sleep (1)
If Mutex.acquire ():
Num=num+1
Print self.name+ ' Set num to ' +str (num) + ' \ n '
Mutex.release ()
Num=0
Mutex=threading. Lock ()
def test ():
For I in range (5):
T=mythread ()
T.start ()
If __name__== ' __main__ ':
Test ()
"""
A simpler deadlock scenario is a thread that "iterates" over the same resource, directly causing a deadlock:
Import threading
Import time
Class MyThread (threading. Thread):
def run (self):
Global num
Time.sleep (1)
If Mutex.acquire (1):
num = num+1
msg = self.name+ ' Set num to ' +str (num)
Print msg
Mutex.acquire ()
Mutex.release ()
Mutex.release ()
num = 0
Mutex = Threading. Lock ()
def test ():
For I in range (5):
t = MyThread ()
T.start ()
if __name__ = = ' __main__ ':
Test ()
To support multiple requests for the same resource in the same thread, Python provides a "reentrant lock": Threading. Rlock. Rlock internally maintains a lock and a counter variable, counter records the number of acquire, so that resources can be require multiple times. Until all the acquire of a thread are release, the other threads can get the resources. In the example above, if you use Rlock instead of lock, a deadlock will not occur:
Import threading
Import time
Class MyThread (threading. Thread):
def run (self):
Global num
Time.sleep (1)
If Mutex.acquire (1):
num = num+1
msg = self.name+ ' Set num to ' +str (num)
Print msg
Mutex.acquire ()
Mutex.release ()
Mutex.release ()
num = 0
Mutex = Threading. Rlock ()
def test ():
For I in range (5):
t = MyThread ()
T.start ()
if __name__ = = ' __main__ ':
Test ()
"""
Mutexes are the simplest thread-synchronization mechanism, and Python-provided condition objects provide support for complex thread synchronization issues. condition is called a conditional variable and provides the wait and notify methods in addition to the acquire and release methods similar to lock. The thread first acquire a condition variable and then determines some conditions. Wait if the condition is not met, and if the condition is met, after some processing changes the condition, the other thread is notified by the Notify method, and the other thread in the wait state will be re-judged after receiving the notification. Constantly repeating this process to solve complex synchronization problems.
You can assume that the condition object maintains a lock (Lock/rlock) and a waiting pool. The thread obtains the condition object through acquire, and when the wait method is called, the thread releases the lock inside the condition and enters the blocked state while recording the thread in the waiting pool. When the Notify method is called, the condition object picks a thread from the waiting pool and notifies it to invoke the Acquire method to fetch the lock.
The constructor of the condition object can accept a Lock/rlock object as a parameter, and if not specified, the condition object creates a rlock on its own internally.
In addition to the Notify method, the Condition object provides a Notifyall method that notifies all threads in the waiting pool to attempt to acquire an internal lock. As a result of the above mechanism, threads in the waiting state can only be awakened by the Notify method, so the role of notifyall is to prevent the thread from ever being in a state of silence.
The classic problem of demonstrating conditional variable synchronization is producer and consumer issues: Suppose a group of producers (Producer) and a group of consumers (Consumer) interact with the product through a single market. The "strategy" of a producer is to produce 100 products on the market if there are less than 1000 remaining products in the market, while the consumer's "strategy" is to consume 3 products if the surplus in the market is more than 100. The code for solving producer and consumer problems with condition is as follows:
Import threading
Import time
Class Producer (threading. Thread):
def run (self):
Global Count
While True:
If Con.acquire ():
If count>1000:
Con.wait ()
Else
count=count+100
Print self.name+ ' Produce 100,count= ' +str (count)
Con.release ()
Time.sleep (1)
Class Customer (threading. Thread):
def run (self):
Global Count
While True:
If Con.acquire ():
If count>100:
count=count-100
Print self.name+ ' consume, count= ' +str (count)
Else
Con.wait ()
Con.release ()
Time.sleep (1)
count=500
Con=threading. Condition ()
def test ():
For I in range (5):
P=producer ()
P.start ()
C=customer ()
C.start ()
Print I
If __name__== ' __main__ ':
Test ()
The default global variable in Python can be read in the function, but cannot be written but
Read-only to con, so don't use global to introduce "" "
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