How to create and call multiple threads in Python

Source: Internet
Author: User
Due to the existence of GIL, although Python can create multiple threads, multithreading cannot work at the same time... well. here let's take a look at the creation of multiple threads in Python and the basic call method. 1. the role of multithreading
In short, multithreading is used to process mutually independent subtasks in parallel, greatly improving the efficiency of the entire task.

2. multithreading related modules and methods in Python
Python provides several modules for multi-threaded programming, including thread, threading, and Queue.
The thread module provides basic thread and lock support. in addition to thread generation, it also provides basic synchronization data structure lock objects, including:
Start_new_thread (function, args kwargs = None) generates a new thread to run the given function
Allocate_lock () allocates a lock object of the LockType.
Exit () causes the thread to exit
Acquire (wait = None) attempts to obtain the lock object
Locked () returns TRUE if the lock object is obtained. otherwise, FALSE is returned.
Release () release lock
Threading provides a higher level and more powerful thread management function
The Thread class indicates the execution object of a Thread.
Lock primitive object
RLock reentrant lock objects so that a single thread can obtain the acquired lock again
The queue module allows you to create a queue data structure that can be used for data sharing among multiple threads.
It can be used for inter-process communication to share data between threads.
The module function queue (size) creates a size-based Queue object.
The queue object function qsize () returns the queue size.
If the empty () queue is empty, True is returned; otherwise, False is returned.
Put (item, block = 0) put the ITEM in the queue. if the block is not 0, the function will always block it into the queue.
Get (block = 0) gets an object from the queue. if it is block, the function will always block until there is an object in the queue.

3. example
Currently, Python lib provides two startup methods for multi-thread programming. one is the start_new_thread method in the basic thread module, which runs a function in the thread, the other is to use the Thread object Thread class that integrates the threading module.
Currently, the start_new_thread () function in the thread module is called in the old version to generate a new thread.
In comparison, thread. start_new_thread (function, (args [, kwargs]) implementation mechanism is actually more similar to C, where the function parameter is the thread function to be called; (args [, kwargs]) is a type of tuples that will be passed to the parameters of the thread function to be created. kwargs is an optional parameter. The end of a newly created thread generally exits automatically after the execution of the thread function ends, or the SystemExit exception is thrown by calling thread. exit () in the thread function to exit the thread.

Print "=================================== thread. start_new_thread start thread ================ "import thread # The Python thread sleep method is not in the thread module, in the time module, import time def inthread (no, interval): count = 0 while count <10: print "Thread-% d, sleep interval: % d, current Time: % s "% (no, interval, time. ctime () # specify the time for the current thread to sleep. The interval value is the floating point number of seconds, which is different from the integer time in Java. sleep (interval) # unlike most advanced languages, Python supports the ++ operator and can only use ++ = to implement count + = 1 else: print "Thread-% d is over" % no # wait until the thread is recycled by PVM, or actively call the exit or exit_thread method to end the Thread thread. exit_thread () # Use the start_new_thread function to start a thread. The first parameter specifies the function to be executed in the thread, and the second parameter is the parameter value transmitted to the specified function in the tuples. start_new_thread (inthread, () # this line must be added during thread execution, and the sleep time must be sufficient to end the thread. for example, # if the sleep time is changed to 20, the exception time may be thrown. sleep (30 )'''

Exceptions may occur when a thread is started using this method.

Unhandled exception in thread started by Error in sys.excepthook: Original exception was: 

Solution: after the thread is started, ensure that the main thread waits for all subthreads to return results before exiting. if the main thread ends earlier than the subthread, whether its subthread is a background thread or not, and throw this exception.
If no response is blocked, time must be called to prevent the main thread from exiting in advance. sleep can sleep the main thread for a long enough time. In addition, the lock mechanism can be used to avoid similar situations. when starting the thread, a lock is applied to each thread, wait until the thread is introduced and release the lock. At the same time, a while loop is used in the main thread of Python to continuously judge that each thread lock has been released.

import thread;  from time import sleep,ctime;  from random import choice  #The first param means the 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 will 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();  

Many introductions say that the Threading module is recommended in the new python version. Currently, it has not been applied...

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.