Threading threading and Process multiprocessing modules

Source: Internet
Author: User
Tags terminates thread class

1. Thread Module Threading

Python provides two standard libraries for multithreading, thread and threading. Thread provides low-level, primitive threads and a lock. The threading is an advanced module that provides the encapsulation of the thread. There are two ways to create a new thread:

How to construct the thread class:
__init__ (Group=none, Target=none, Name=none, args= (), Kwargs=none, Verbose=none)
Parameter description: Group: Thread groups, currently not implemented, the library reference must be a hint of none. Target: The method to execute; Name: thread name; Args/kwargs: the parameter to pass in the method.
Instance methods owned by the thread class:
IsAlive (): Returns whether the thread is running. Running refers to the start-up, before terminating. GetName (name)/setname (name): Gets/sets the thread name. Isdaemon (BOOL)/setdaemon (BOOL): Gets/Sets whether it is a daemon thread. The initial value is inherited from the thread that created the thread, and the program terminates when no non-daemon thread is still running. Start (): Starts the thread. Join ([timeout]): Blocks the thread of the current context until the thread calling this method terminates or arrives at a specified wait time of timeout (optional parameter). That is, the current thread waits for the thread to call join () to execute, or to reach the specified time.

Method One: Create the threading directly. The thread class object that is initialized when the callable object is passed in as a parameter.

Attention:

t = thread (target = run, args = ("This is a", "thread") the sentence simply creates a thread that does not execute the thread and the thread is in a new state. T.start () #启动线程启动线程, at which point the thread is still not running, but is in a ready state.


Method Two: By inheriting the thread class, overriding its __init__( ) methods and the Run method.

Due to the creation of two concurrently executing threads t1 and T2, the execution time of the concurrent threads is uncertain, and the time of execution is uncertain, so the order in which the results are printed is uncertain. Each execution is likely to have different results.

Attention:

Inheriting the new class of the thread class the Mythread constructor must call the constructor of the parent class in order to produce parameters in the parent class's constructor to produce the parameters required by the thread. In the new class, if you need another parameter, add it directly to the constructor method.
At the same time, in the new class, when overriding the parent class's Run method, it defaults to no parameters, if you need to give it parameters, you need to specify in the constructor of the class, because the process of thread execution, the Run method is called by itself, without our manual call, so we can not directly to pass parameters, Parameters can only be set in the constructor method, and then called in the Run method. 2, multiprocessing module thread multiprocessing module and the same module used by the process. The use method is basically the same, except that the imported pool from the multiprocessing import pool represents the process pool;
From multiprocessing.dummy import pool Such an imported pool represents a thread pool. This allows the concurrency within the thread to be implemented. Line pooling Example: Process Pool Sample:
From multiprocessing import pooldef F (x):    return x*xif __name__ = = ' __main__ ': With    Pool (5) as P:        print (P.map (f, [1, 2, 3])) Results output: [1, 4, 9]

In multiprocessing, the process object is created by creating it and then calling its start () method to generate the processes.

From multiprocessing import processimport osdef info (title):    Print (    ' module name: ', __name__)    print (' Parent process: ', Os.getppid ())    print (' Process ID: ', os.getpid ()) def f (name):    info (' function f ')    print (' Hello ', name) if __name__ = = ' __main__ ':    info (' main line ')    p = Process (target=f, args= (' Bob ',))    P.start ()    p.join ()

Threading threading and Process multiprocessing modules

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.