Python threading multi-thread programming example, threading multi-thread programming

Source: Internet
Author: User

Python threading multi-thread programming example, threading multi-thread programming

Python multithreading can be implemented in two ways:

Functions and threads

1. Functions

Call the start_new_thread () function in the thread module to create a thread and tell the thread what to do in the form of a thread function.

Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-
Import thread
Def f (name ):
# Defining thread Functions
Print "this is" + name
 
If _ name _ = '_ main __':
Thread. start_new_thread (f, ("thread1 ",))
# Use start_new_thread () to call thread functions and other parameters
While 1:
Pass

However, this method does not find other auxiliary methods for the time being. You must use the while 1 method to solve the problem even when the main thread waits.

2. Thread class

Call the threading module and create a subclass of threading. Thread to obtain the custom Thread class.
Copy codeThe Code is as follows:
#-*-Coding: UTF-8 -*-
Import threading
Class Th (threading. Thread ):
Def _ init _ (self, name ):
Threading. Thread. _ init _ (self)
Self. t_name = name
# Calling the parent class Constructor
 
Def run (self ):
# Rewrite the run () function. By default, the thread starts to execute this function.
Print "This is" + self. t_name
 
If _ name _ = '_ main __':
Thread1 = Th ("Thread_1 ")
Thread1.start ()
# Start () function to start the thread and automatically execute the run () function

Inheritance functions of the threading. Thread class:
GetName () Get the thread object name
SetName () sets the thread object name
Join () command after running after the called thread ends
SetDaemon (bool) blocking mode, True: the parent thread does not wait for the end of the sub-thread, False wait, the default is False
IsDaemon () determines whether the Sub-thread ends with the parent thread, that is, the value set by setDaemon ().
IsAlive () determines whether the thread is running

Instance

Copy codeThe Code is as follows:
Import threading
Import time
Class Th (threading. Thread ):
Def _ init _ (self, thread_name ):
Threading. Thread. _ init _ (self)
Self. setName (thread_name)
 
Def run (self ):
Print "This is thread" + self. getName ()
For I in range (5 ):
Time. sleep (1)
Print str (I)
Print self. getName () + "is over"

Join () blocking wait

Copy codeThe Code is as follows:
If _ name _ = '_ main __':
Thread1 = Th ("T1 ")
Thread1.start ()
# Thread1.join ()
Print "main thread is over"

Without thread1.join (), the following result is obtained:
Copy codeThe Code is as follows:
This is thread T1
Main thread is over
0
1
2
T1 is over

Do not wait until thread1 is complete. Execute the following statement.
After thread1.join () is added, the following results are obtained:
Copy codeThe Code is as follows:
This is thread T1
0
1
2
T1 is over
Main thread is over

The following statement is executed only when thread1 ends.

Main thread waiting

Copy codeThe Code is as follows:
If _ name _ = '_ main __':
Thread1 = Th ("T1 ")
Thread1.setDaemon (True)
# Set this amount before thread execution
Thread1.start ()
Print "main thread is over"

Error: Exception in thread T1 (most likely raised during interpreter shutdown ):
That is, the main thread ends without waiting for the Child thread.

Multiple subthreads
Copy codeThe Code is as follows:
If _ name _ = '_ main __':
For I in range (3 ):
T = Th (str (I ))
T. start ()
Print "main thread is over"

Here t can process multiple threads at the same time, that is, t is the thread handle, and the re-assignment does not affect the thread.

It is strange that other threads will not be executed when t. run () is run. Although not clear, use start. For the moment, it is understood that start () is non-blocking parallel, while run is blocking.

Thread lock

Threading provides a thread lock for thread synchronization.
Copy codeThe Code is as follows:
Import threading
Import time
Class Th (threading. Thread ):
Def _ init _ (self, thread_name ):
Threading. Thread. _ init _ (self)
Self. setName (thread_name)
 
Def run (self ):
ThreadLock. acquire ()
# Run the lock again
Print "This is thread" + self. getName ()
For I in range (3 ):
Time. sleep (1)
Print str (I)
Print self. getName () + "is over"
ThreadLock. release ()
# Release a lock
If _ name _ = '_ main __':
ThreadLock = threading. Lock ()
# Setting global locks
Thread1 = Th ('thread _ 1 ')
Thread2 = Th ('thread _ 2 ')
Thread1.start ()
Thread2.start ()

Expected result:
Copy codeThe Code is as follows:
This is thread Thread_1
0
1
2
Thread_1 is over
This is thread Thread_2
0
1
2
Thread_2 is over


In the python threading module, after multiple threads are generated, how does one obtain the string returned after the thread is executed?

Multi-threaded/multi-process communication or callback, rather than directly returning results. This is easy to understand, because if you use the returned results to assign values to a variable, you must wait until the function ends and your program will be blocked, this eliminates the significance of multi-threaded/multi-process blocking.
Communication can be event-driven or transmitted using thread-safe data structures (such as Queue, 0mq, and rabbitMQ ), callback means that after a program is executed, you can call another function to process the next step.

A multi-threaded program written in python executes the thread created by multiple threads cyclically. However, after the program is executed for a certain period of time

It seems that your fifth thread is suspended, which makes it impossible to release the lock resource.

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.