Pythonthreading multi-thread programming example

Source: Internet
Author: User
This article mainly introduces Pythonthreading multi-threaded programming examples. This article describes examples of using functions and threads to implement multi-threaded programming. you can refer to the following two methods to implement Python multithreading:

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.

The 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.

The 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

The 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

The 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:

The 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:

The 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

The 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

The 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.

The 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:

The 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

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.