Python Multi-threaded learning (top)

Source: Internet
Author: User
Tags thread class

Recently in the Learning Python multi-threading, write the essay as a review. It is also highly recommended that you take a look at the Python core programming book, which can help you learn the steps of Python.

One. Basic concepts:

1. Threads:

Threads are also known as lightweight processes, where information can be shared between threads, and threads can be viewed as a mini-process of the main process or the ' main thread '.

2. Process:

Processes are also known as heavyweight processes, and processes are independent, and inter-process shared information is carried out through interprocess communication (IPC).

3. Sync:

Synchronization refers to a task after the completion of another task, the next, is a next to each other, such as you eat in the cafeteria, a window of the dishes delicious, there are many people lined up, only the former one after the meal, after a meal can be played.

4. Async:

Asynchronous refers to a number of tasks at the same time, such as: Canteen has a lot of rice window, many people can be at the same time to play rice.

5. I/O:

I/O is an abbreviation for input/output, which means read and write.

6. I/O intensive code (I/O bound):

I/O intensive refers to the program to read and write a lot, the calculation is relatively small.

7. Compute-Intensive code (CPU bound):

Computation-intensive means that the program is mainly calculated, and read and write operations are less.

8. Concurrency and parallelism:

Concurrent CPUs < threads, concurrency refers to the execution of tasks within the same interval of time.

Number of concurrent CPUs > threads, parallel means that multiple tasks are executed simultaneously.

Two. Python and Threads:

The execution of the Python code is controlled by the Python virtual machine (the interpreter main loop).

Python also has a Gil (Global interpreter Lock), which is used to control only one thread executing.

Gil Lock Execution Process:

Lock

Perform

Release

Returns to the first step.

When Python executes multiple threads, it actually executes the task within the same interval of time, each task executes for a short period of time, then hangs, executes the next, until the last, and then starts from the first, so reciprocating, until the end.

Python is more friendly than computationally intensive for I/O intensive. Reason: Python in the implementation of I/O-intensive programs, mainly for file read and write, and less computation, each task can be computed at the same time to the other to complete the calculation of read and write, and compute-intensive for the calculation of more, always occupy the CPU, resulting in inefficient processing, so the computation-intensive is not friendly.

Three. Threading Module

For multithreading there are thread modules and threading modules. Thread module when executing multi-threading, without locking, if the main thread ends, and the child threads are not finished, the child threads will be forced to stop, resulting in no running results. It is recommended to use the threading module for multithreaded learning.

1. Add Thread: Threading. Thread (target= function name, args= (required parameter passed in))

The thread class can also pass in the name, giving it a name.

2. Determine if the thread is active: is_alive ()

3. Get the number of threads: Threading.active_count ()

4. Get current thread: Threading.current_thread ()

5. Get the thread name:. Name

6. Wait for the thread:. Join ()

Waiting and not waiting:

Wait:

1 defa_1 ():2     Print('AAAAA')3Time.sleep (3)4     Print('AAAAA')5 defa_2 ():6     Print('bbbbb')7Time.sleep (5)8     Print('bbbbb')9 defMain ():Ten     Print('..... start ....') OneT1 = Threading. Thread (target=a_1) AT2 = Threading. Thread (target=a_2) - T1.start () - T2.start () the     Print('..... end ... .') -  - if __name__=='__main__': - Main () +  -  + Operation Result: A  at ..... start .... - AAAAA - bbbbb - ..... end ... . - AAAAA - bbbbb in  -Process finished with exit code 0

As you can see from the running results, running results is not the result we want when we don't add the wait.

Here's the wait for No. Join ():

defMain ():Print('..... start ....') T1= Threading. Thread (target=a_1) T2= Threading. Thread (target=a_2) T1.start () T2.start () time.sleep (8)    Print('..... end ... .')if __name__=='__main__': Main () Run result: .... start....aaaaabbbbbaaaaabbbbb....end .... Process finished with exit code 0

Run the next operation by adding the Time.sleep () statement so that the main thread waits for the child thread to run. Print content ... start .... And ... end ... Between.

Here is the use of. Join () to wait.

def main ():    print (' ... ')    t1 = Threading. Thread (target=a_1)    t2 = Threading. Thread (target=a_2)    T1.start ()    T2.start ()    t1.join ()    t2.join ()    print (' ... ') if __name_ _ = = ' __main__ ':    main () Run result: .... start....aaaaabbbbbaaaaabbbbb....end .... Process finished with exit code 0

As you can see, adding the Sleep () and join () effects is the same, but it is recommended to use. Join (), because waiting with sleep () waits while running the program, and it is more troublesome to wait until you know the waiting time. Join () is more convenient.

To create a threading method:

<1> passing functions to the thread class

<2> passing an instance class to the thread class

<3> create a subclass, inherit the thread class, and then pass the function to the child class

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

In the case of no multi-threading:

Import datetime
Def num_1 ():
Print (' Start ... 1 ')
Time.sleep (2)
Print (' End ... 1 ')
Def num_2 ():
Print (' Start ... 2 ')
Time.sleep (4)
Print (' End ... 2 ')

def main ():
A = Datetime.datetime.now ()
Print (' ... ...... ............)
Num_1 ()
Num_2 ()
Print (' ... ..... ...............)
b = Datetime.datetime.now ()
p = (b-a). seconds
Print (' Run%s sec '% p)
if __name__ = = ' __main__ ':
Main ()

Create two functions, print different content separately, and finish printing execution time when the program executes.

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

For <1>

Here is the sample code:. Join () is the main thread that waits for the child thread to complete after the next action is taken.

1 ImportThreading2 Importdatetime3 #transfer function (1)4 defnum (nu,se):5     Print('%s Start'%nu)6 time.sleep (SE)7     Print('%s End'%nu)8 9Time_list = [2,4]Ten defMain (): OneA =Datetime.datetime.now () A     Print('..... start ... ..') -Thread_list = [] -      forXinchRange (len (time_list)): the         t = Threading. Thread (target=num,args= (x,time_list[x) ) - thread_list.append (t) -      forXinchthread_list: - X.start () +      forXinchthread_list: - X.join () +     Print('..... end ... ..') Ab =Datetime.datetime.now () atp = (b-a). Seconds -     Print('Run%s seconds'%p) - if __name__=='__main__': -Main ()

<2> add an instance class.

classnew_1 ():def __init__(self,num,se): Self.num=Num self.se=SEdef __call__(self):returnSelf.num (*self.se)PassdefMain (): a=Datetime.datetime.now ()Print('... start ...') Thread_list= []     forXinchRange (len (time_list)): T= Threading. Thread (Target=new_1 (num, (x+1, Time_list[x]))) Thread_list.append (t) forXinchThread_list:x.start () forXinchThread_list:x.join ()Print('... end ...') b=Datetime.datetime.now () p= (b-a). SecondsPrint('Run%s seconds'%p)if __name__=='__main__': Main ()
Operation Result:

... start ...
1 start
2 start
1 End
2 End
... end ...
Run for 4 seconds

Process finished with exit code 0

3. Inherit the thread class and pass the content into the subclass.

Here's the code:

#传递函数 (1) def num (nu,se):    print ('%s  start '% nu)    time.sleep (SE)    print ('%s  end '% nu) time_list = [ 2,4]class new_2 (Threading. Thread):    def __init__ (self,num,se):        super (). __init__ ()        self.num = num        self.se = SE    def run (self) :        return Self.num (*self.se)    passdef Main ():    a = Datetime.datetime.now ()    print (' ... ')    thread_list = [] for    x in range (len (time_list)):        t = new_2 (num, (x,time_list[x]))        Thread_ List.append (t) for    x in thread_list:        X.start () for    x in thread_list:        x.join ()    print (' ... end ... ')    B = Datetime.datetime.now ()    p = (b-a). Seconds    Print (' Run%s sec '% p) if __name__ = = ' __main__ ':    Main () Run Result: ... start ... 0  start1  start0  end1  end...end ... Run 4 second process finished with exit code 0

For the above three ways to add threads, you can choose according to their own preferences, others do understand.

If there is something wrong, please give me your correct question.

Thank you for reading.

Python Multi-threaded learning (top)

Related Article

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.