[Python] Getting started with multithreading

Source: Internet
Author: User

Original: http://blog.csdn.net/ice110956/article/details/28421807

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

[Python]View PlainCopy 
  1. #-*-Coding:utf-8-*-
  2. Import Thread
  3. def f (name):
  4. #定义线程函数
  5. Print "This is" + name
  6. if __name__ = = ' __main__ ':
  7. Thread.start_new_thread (F, ("Thread1",))
  8. #用start_new_thread () calling thread functions and other parameters
  9. while 1:
  10. 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.

[Python]View PlainCopy 
  1. #-*-Coding:utf-8-*-
  2. Import threading
  3. Class Th (threading. Thread):
  4. def __init__ (self, name):
  5. Threading. Thread.__init__ (self)
  6. self.t_name = name
  7. #调用父类构造函数
  8. def run (self):
  9. #重写run () function, the thread starts execution from this function by default
  10. Print "This is" + self.t_name
  11. if __name__ = = ' __main__ ':
  12. Thread1 = Th ("Thread_1")
  13. Thread1.start ()
  14. #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

[Python]View PlainCopy 
  1. Import threading
  2. Import time
  3. Class Th (threading. Thread):
  4. def __init__ (self, thread_name):
  5. Threading. Thread.__init__ (self)
  6. self.setname (thread_name)
  7. def run (self):
  8. Print "This is thread" + self.getname ()
  9. For I in range (5):
  10. Time.sleep (1)
  11. Print str (i)
  12. print self.getname () + " is Over"
Join () Blocking wait

[Python]View PlainCopy  
    1. if __name__ = = ' __main__ ':
    2. Thread1 = Th ("T1")
    3. Thread1.start ()
    4. #thread1. Join ()
    5. print "main thread is over"

Without Thread1.join (), the following results are obtained:

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:

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

[Python]View PlainCopy 
    1. if __name__ = = ' __main__ ':
    2. Thread1 = Th ("T1")
    3. Thread1.setdaemon (True)
    4. #要在线程执行之前就设置这个量
    5. Thread1.start ()
    6. 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

[Python]View PlainCopy 
    1. if __name__ = = ' __main__ ':
    2. For I in range (3):
    3. t = Th (str (i))
    4. T.start ()
    5. 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.

[Python]View PlainCopy 
  1. Import threading
  2. Import time
  3. Class Th (threading. Thread):
  4. def __init__ (self, thread_name):
  5. Threading. Thread.__init__ (self)
  6. self.setname (thread_name)
  7. def run (self):
  8. Threadlock.acquire ()
  9. #获得锁之后再运行
  10. Print "This is thread" + self.getname ()
  11. For I in range (3):
  12. Time.sleep (1)
  13. Print str (i)
  14. print self.getname () + " is Over"
  15. Threadlock.release ()
  16. #释放锁
  17. if __name__ = = ' __main__ ':
  18. Threadlock = Threading. Lock ()
  19. #设置全局锁
  20. Thread1 = Th (' thread_1 ')
  21. Thread2 = Th (' thread_2 ')
  22. Thread1.start ()
  23. Thread2.start ()

Get results:

This is thread thread_1

0

1

2

Thread_1 is Over

This is thread thread_2

0

1

2

Thread_2 is Over

[Python] Getting started with multithreading

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.