Multi-threading creation and basic invocation methods in Python _python

Source: Internet
Author: User

1. The role of multithreading
in short, multithreading is a parallel process of independent subtasks, thus greatly improving the efficiency of the entire task.

2. Multithreading-related modules and methods in Python
Python provides several modules for multithreaded programming, including thread,threading and queue
The thread module provides basic thread and lock support, and provides basic synchronization data structure lock objects in addition to thread generation, including:
Start_new_thread (function, args kwargs=none) produces a new thread to run the given function
Allocate_lock () assigns a locktype type of lock object
Exit () Let the thread exit
Acquire (Wait=none) attempt to acquire lock object
Locked () returns True if a lock object is obtained or false
Release () Free lock
Threading provides a higher level of more powerful threading management capabilities
The thread class represents an object of execution for a thread
Lock Primitive Object
Rlock can be reentrant to lock objects so that a single thread can again get the acquired lock
The queue module allows users to create a queue data structure that can be used to share data between multiple threads
Can be used to communicate between processes, allowing data to be shared among threads
Module function queue (size) creates a queue object of size
Queue Object Function Qsize () returns the size of queues
Returns True if the empty () queue is null, or False
Put (item, block=0) the item into the queue, block is not 0, the function will be blocked into the queue
Get (Block=0) takes an object from the queue, and if given block, the function blocks until there is an object in the queue.

3. Example
currently in Python's lib, there are two ways to start multithreaded programming, one is the Start_new_thread method in the basic thread module, which runs a function in the thread. The other is threading object thread classes that use integrated threading modules. The
is currently used, in the older version, to invoke the Start_new_thread () function in the thread module to produce a new thread
, Thread.start_new_thread (function, Args[,kwargs ) The implementation mechanism is actually more like C, where the function parameter is the thread functions to be invoked; (Args[,kwargs]) is the tuple type that will be passed to the parameters to be created, where Kwargs is an optional parameter. The newly created thread end generally relies on the execution of the thread function to end the automatic exit, or call Thread.exit () in a thread function to throw systemexit exception, to achieve the thread exit.

print "=======================thread.start_new_thread boot thread ============="  
import thread  
# The python thread-sleep method is not in the thread module, but instead is the  
import time  
def inthread (No,interval) under the time module:  
  count=0 while  
  COUNT<10:  
    print "thread-%d, hibernate interval:%d,current time:%s" (No,interval,time.ctime ())  
    #使当前线程休眠指定时间, Interval is a floating-point number of seconds, different from the time.sleep in Java  
    (interval)  
    #Python不像大多数高级语言一样支持 + + operator, can only be implemented with + +  
    count+=1  
  Else:  
    print "thread-%d is Over"%no  
    #可以等待线程被PVM回收, or actively call the exit or Exit_thread method to end a thread  
    thread.exit_ Thread ()  
#使用start_new_thread函数可以简单的启动一个线程, the first parameter specifies the function to execute in the thread, and the second parameter is the parameter value passed to the specified function by the tuple type  
thread.start_new_ Thread (Inthread, (1,2))  
  #线程执行时必须添加这一行, and the time of sleep must be sufficient for the thread to end, as in this case  
  #如果休眠时间改为20, an exception could be thrown  
Time.sleep (30 )  
'''  

When you start a thread using this method, you may receive an exception

Unhandled exception in thread started by 
Error in Sys.excepthook: 
Original exception is: 

Resolve: After starting the thread, make sure that the main thread waits for all the child threads to return the result and then exits, and if the mainline Cheng thread ends early, regardless of whether its child thread is a background thread, it will break, throwing the exception
if there is no response blocking wait, You must call Time.sleep to make the main thread hibernate long enough, and you can also use the lock mechanism to avoid similar situations by adding a lock to each thread when the thread is started, until the thread runs the introduction and then releases the lock. At the same time, a while loop is used in the main thread of Python to constantly determine that each lock has been released.

import thread;  
From time import sleep,ctime;  
From random import choice  
#The param means thread number #The second param means how  
long it sleep  
The third param means the Lock  
def Loop (nloop,sec,lock):  
  print "Thread", Nloop, "Start and'll Sleep", sec;  
  Sleep (sec);  
  Print "Thread", Nloop, "End", sec;  
  Lock.release ();  
  
def main ():  
  seconds=[4,2];  
  Locks=[];  
  For I in range (len (seconds)):  
    Lock=thread.allocate_lock ();  
    Lock.acquire ();  
    Locks.append (lock);  
      
  Print "Main Thread begins:", CTime ();  
  For I,lock in Enumerate (locks):  
    Thread.start_new_thread (Loop, i,choice (seconds), lock);  
  For lock in Locks: while  
    lock.locked (): Pass   
      ;  
  Print "Main Thread ends:", CTime ();  
  
If __name__== "__main__":  
  main ();  

A lot of introduction said in the new Python version of the recommended use of threading module, currently not applied to ...

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.