Defining and invoking threads in Python through the threading module

Source: Internet
Author: User
Defining Threads

The simplest method: Use target to specify the target function to be executed by the thread and start with start ().

Grammar:

Class Threading. Thread (Group=none, Target=none, Name=none, args= (), kwargs={})

Group constant is None, reserved for future use. Target is the name of the function to execute. Name is the thread name and defaults to Thread-n, which is usually used by default. But the server-side program thread does not have the same function, it is recommended to name.

#!/usr/bin/env python3# coding=utf-8import threadingdef function (i):  print ("function called by thread {0}". Format ( i)) threads = []for i in Range (5):  t = Threading. Thread (Target=function, args= (i,))  threads.append (t)  T.start ()  t.join ()

Execution Result:

$./threading_define.py

function called by thread 0function called by thread 1function called by thread 2function called by thread 3function Calle D by thread 4

Determining the current thread

#!/usr/bin/env python3# coding=utf-8import threadingimport timedef first_function ():  print ( Threading.currentthread (). GetName () + str (' is starting \ n '))  Time.sleep (3)  print (Threading.currentthread () . GetName () + str (' is Exiting \ n '))  def second_function ():  print (Threading.currentthread (). GetName () + str (' is Starting \ n '))  Time.sleep (2)  print (Threading.currentthread (). GetName () + str (' is Exiting \ n '))  def third _function ():  print (Threading.currentthread (). GetName () +\  str (' is starting \ n '))  time.sleep (1)  Print (Threading.currentthread (). GetName () + str (' is Exiting \ n '))  if __name__ = = "__main__":  T1 = Threading. Thread (name= ' first_function ', target=first_function)  t2 = Threading. Thread (name= ' second_function ', target=second_function)  t3 = Threading. Thread (name= ' third_function ', target=third_function)  T1.start ()  T2.start ()  T3.start ()

Execution Result:

$./threading_name.py

First_function is starting second_function are starting third_function is starting third_function are Exiting Second_functio N is Exiting first_function is Exiting

Use with the logging module:

#!/usr/bin/env python3# coding=utf-8import loggingimport threadingimport timelogging.basicconfig (  level=logging . DEBUG,  format= ' [% (LevelName) s] (% (threadname) -10s)% (message) s ',  )  def worker ():  logging.debug (' Starting ')  Time.sleep (2)  logging.debug (' Exiting ')  def my_service ():  logging.debug (' starting ')  Time.sleep (3)  logging.debug (' Exiting ')  t = Threading. Thread (name= ' My_service ', target=my_service) W = threading. Thread (name= ' worker ', target=worker) W2 = Threading. Thread (target=worker) # Use default Namew.start () W2.start () T.start ()

Execution Result:

$./threading_names_log.py[debug] (worker  ) starting

[DEBUG] (Thread-1) Starting[debug] (My_service) Starting[debug] (worker  ) Exiting[debug] (Thread-1) Exiting[debug] (My_service) Exiting


Using Threads in subclasses

Our threads are all created in the form of structured programming. By integrating threading. The thread class can also create threads. The thread class first finishes some basic initialization and then calls its run (). The run () method invokes the target function passed to the constructor.

#!/usr/bin/env python3# coding=utf-8import loggingimport threadingimport timeexitflag = 0class myThread (threading. Thread):  def __init__ (self, ThreadID, name, counter):    Threading. Thread.__init__ (self)    self.threadid = ThreadID    self.name = name    Self.counter = Counter      def run (self):    print ("starting" + Self.name)    print_time (Self.name, Self.counter, 5)    print ("Exiting" + self.name)    def print_time (ThreadName, Delay, counter): While  counter:    if Exitflag:      thread.exit ()    Time.sleep (delay)    print ("%s:%s"% (ThreadName, Time.ctime (Time.time ())))    Counter-= 1    # Create New Threadsthread1 = MyThread (1, "Thread-1", 1) thread2 = MyThread (2, "Thread-2", 2) # Start new Threadsthread1.start () thread2. Start () print ("Exiting Main Thread")

Execution Result:

$./threading_subclass.py

Starting thread-1starting thread-2exiting Main ThreadThread-1: Tue Sep 11:03:21 2015thread-2: Tue Sep 11:03:22 2015T Hread-1: Tue Sep 11:03:22 2015thread-1: Tue Sep 11:03:23 2015thread-2: Tue Sep 11:03:24 2015thread-1: Tue Sep 15 11:03:24 2015thread-1: Tue Sep 11:03:25 2015Exiting thread-1thread-2: Tue Sep 11:03:26 2015thread-2: Tue Sep 15 11:0 3:28 2015thread-2: Tue Sep 11:03:30 2015Exiting Thread-2

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.