Python Threading Multithreaded Programming example

Source: Internet
Author: User
There are two ways to implement multithreading in Python:

function, Thread class

1. Functions

Call the Start_new_thread () function in the thread module to create a thread that tells the thread what to do in the form of a thread function

Copy the Code code as follows:


#-*-Coding:utf-8-*-
Import Thread
def f (name):
#定义线程函数
Print "This is" + Name

if __name__ = = ' __main__ ':
Thread.start_new_thread (F, ("Thread1",))
#用start_new_thread () calling thread functions and other parameters
While 1:
Pass

However, this method has not been able to find other auxiliary methods, even the main thread waits to use while 1 this method to solve.

2. Threading Class

Call the threading module to create the threading. The subclass of thread to get the custom thread class.
Copy the Code code as follows:


#-*-Coding:utf-8-*-
Import threading
Class Th (threading. Thread):
def __init__ (self, name):
Threading. Thread.__init__ (self)
Self.t_name = Name
#调用父类构造函数

def run (self):
#重写run () function, the thread starts execution from this function by default
Print "This is" + self.t_name

if __name__ = = ' __main__ ':
Thread1 = Th ("Thread_1")
Thread1.start ()
#start () function starts the thread and executes the run () function automatically

Threading. Inheritable functions for the Thread class:
GetName () Gets the thread object name
SetName () Set Thread object name
Join () wait for the calling thread to end before running the command
Setdaemon (BOOL) blocking mode, True: Parent thread does not wait for child threads to end, false waits, default is False
Isdaemon () Determines whether the child thread ends with the parent thread, that is, the value set by the Setdaemon ()
IsAlive () Determine if the thread is running

Instance

Copy the Code code as follows:


Import threading
Import time
Class Th (threading. Thread):
def __init__ (self, thread_name):
Threading. Thread.__init__ (self)
Self.setname (Thread_name)

def run (self):
Print "This is thread" + self.getname ()
For I in range (5):
Time.sleep (1)
Print str (i)
Print self.getname () + "is Over"

Join () Blocking wait

Copy the Code code as follows:


if __name__ = = ' __main__ ':
Thread1 = Th ("T1")
Thread1.start ()
#thread1. Join ()
Print "Main thread is over"

Without Thread1.join (), the following results are obtained:
Copy the Code code as follows:


This is thread T1
Main thread is over
0
1
2
T1 is Over


Do not wait for Thread1 to complete after executing the statement.
Add Thread1.join () to get the following result:
Copy CodeThe code is as follows:


This is thread T1
0
1
2
T1 is Over
Main thread is over


Blocking waits for thread1 to end before executing the following statement

Main thread Wait

Copy the Code code as follows:


if __name__ = = ' __main__ ':
Thread1 = Th ("T1")
Thread1.setdaemon (True)
#要在线程执行之前就设置这个量
Thread1.start ()
Print "Main thread is over"

Error: Exception in thread T1 (most likely raised during interpreter shutdown):
That is, the main thread does not wait for the child threads to end.

Multiple Child threads
Copy the Code code as follows:


if __name__ = = ' __main__ ':
For I in range (3):
t = Th (str (i))
T.start ()
Print "Main thread is over"

Here t can handle multiple threads at the same time, i.e. T is the thread handle, and re-assignment does not affect the thread.

It is strange here that when you run T.run (), no more threads are executed. Although it is unclear, use Start (). It is understood that start () is non-blocking parallel, while run is blocked.

Thread Lock

The threading provides the thread lock, which enables threading synchronization.
Copy the Code code as follows:


Import threading
Import time
Class Th (threading. Thread):
def __init__ (self, thread_name):
Threading. Thread.__init__ (self)
Self.setname (Thread_name)

def run (self):
Threadlock.acquire ()
#获得锁之后再运行
Print "This is thread" + self.getname ()
For I in range (3):
Time.sleep (1)
Print str (i)
Print self.getname () + "is Over"
Threadlock.release ()
#释放锁
if __name__ = = ' __main__ ':
Threadlock = Threading. Lock ()
#设置全局锁
Thread1 = Th (' thread_1 ')
Thread2 = Th (' thread_2 ')
Thread1.start ()
Thread2.start ()

Get results:
Copy the Code code as follows:


This is thread thread_1
0
1
2
Thread_1 is Over
This is thread thread_2
0
1
2
Thread_2 is Over
  • 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.