Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How python threads create and pass parameters

2025-04-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to create and transmit parameters for python threads. The editor thinks it is very practical, so I share it for you as a reference. I hope you can get something after reading this article.

one。 Thread interpretation

A thread is the minimum scheduling unit of cpu, and there are at least one or more threads in a program (as for not explaining the process for the time being, it will be explained in more detail later)! The use of threads in development can make programs run more efficiently, and multithreading is similar to executing several different blocks of code at the same time.

two。 Thread creation and startup 1. Import thread module

one

two

# Import thread threading module

Import threading

two。 Create and initialize threads

Call the default function Thread in the threading module, create and initialize the thread, and return the thread handle. If you have forgotten about the default function, please go back to the declaration and definition of the python function and review the default parameters.

one

two

# create and initialize the thread and return the thread handle

T = threading.Thread (target= function name)

3. Start thread

The start () function is called by initializing the returned thread handle to start the thread, which automatically executes the code inside the function corresponding to target when the thread is created:

one

two

# start thread

T.start ()

Combining the above three points, the following code explains the python thread thread in detail:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

thirty-two

thirty-three

thirty-four

thirty-five

thirty-six

thirty-seven

thirty-eight

thirty-nine

#! usr/bin/env python

#-*-coding:utf-8 _ *-

"

@ Author: how to solve the problem

Blog (personal blog address): shuopython.com

@ WeChat Official Account (official Wechat account): ape says python

@ Github:www.github.com

@ File:python_thread.py

@ Time:2019/10/16 21:02

@ Motto: if you don't accumulate steps, you can't reach thousands of miles. If you don't accumulate small streams, you can't become rivers and seas. The splendor of program life needs to be accumulated unremittingly.

"

# Import thread threading module

Import threading

# Import built-in module time

Import time

Def wash_clothes ():

Print ("laundry begins...")

# sleep 5 seconds. Default is in seconds.

Time.sleep (5)

Print ("laundry finished...")

Def clean_room ():

Print ("start cleaning the room...")

# sleep 5 seconds. Default is in seconds.

Time.sleep (5)

Print ("cleaning the room is done.")

If _ name__ = = "_ _ main__":

# create a thread and initialize-- the thread executes the code in wash_clothes

T1 = threading.Thread (target=wash_clothes)

# create a thread and initialize-- the thread executes the code in clean_room

T2 = threading.Thread (target=clean_room)

T1.start ()

T2.start ()

Output result:

one

two

three

four

The laundry begins.

Start cleaning the room.

The laundry is done.

The cleaning of the room is finished.

Running the program can find that it takes a total of 5 seconds from the beginning to the end of the program! Pay attention to the output log:

One: the laundry start and the room cleaning start almost at the same time, both events are carried out at the same time.

Two: the program stops for 5 seconds

Three: washing clothes and cleaning the room are done almost at the same time

Of course, you can also call the wash_clothes function according to the previous study. When you call the clean_room function, you can also output the content, but it takes about 10 seconds. The sample code is as follows:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

# Import built-in module time

Import time

Def wash_clothes ():

Print ("laundry begins...")

# sleep 5 seconds. Default is in seconds.

Time.sleep (5)

Print ("laundry finished...")

Def clean_room ():

Print ("start cleaning the room...")

# sleep 5 seconds. Default is in seconds.

Time.sleep (5)

Print ("cleaning the room is done.")

If _ name__ = = "_ _ main__":

Wash_clothes ()

Clean_room ()

Output result:

one

two

three

four

The laundry begins.

The laundry is done.

Start cleaning the room.

The cleaning of the room is finished.

Running the program can find that it takes a total of 10 seconds from the beginning to the end of the program! Pay attention to the output log:

One: start washing clothes

Two: the program stopped for 5 seconds

Three: the laundry is finished and the cleaning of the room begins

Four: the program stops for 5 seconds

Five: the end of cleaning the room and the end of the program

Thus it can be seen that multithreading can run multiple tasks at the same time, which is far more efficient than single threading!

three。 Thread passing parameters

In the above demo, we didn't pass parameters to the thread, so what if we need to pass parameters in the thread?

There are two default parameters args and kwargs in the threading.Thread () function. Args is a tuple type, kwargs is a dictionary type, and the default value is empty. In addition, you can also set the name of the thread. The function declaration is as follows:

(ps: if you have forgotten about the default function, please go back to the declaration and definition of the python function and review the default parameters)

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

Def _ _ init__ (self, group=None, target=None, name=None

Args= (), kwargs=None, *, daemon=None):

This constructor should always be called with keyword arguments. Arguments are:

* group* should be None; reserved for future extension when a ThreadGroup

Class is implemented.

* target* is the callable object to be invoked by the run ()

Method. Defaults to None, meaning nothing is called.

* name* is the thread name. By default, a unique name is constructed of

The form "Thread-N" where N is a small decimal number.

* args* is the argument tuple for the target invocation. Defaults to ().

* kwargs* is a dictionary of keyword arguments for the target

Invocation. Defaults to {}.

If a subclass overrides the constructor, it must make sure to invoke

The base class constructor (Thread.__init__ ()) before doing anything

Else to the thread.

"

The sample code is as follows:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

# Import thread threading module

Import threading

# Import built-in module time

Import time

Def wash_clothes (* args,**kargcs):

Print ("wash_clothes:", args)

Print ("wash_clothes:", kargcs)

Def clean_room (* args,**kargcs):

Print ("clean_room:", args)

Print ("clean_room:", kargcs)

If _ name__ = = "_ _ main__":

T1 = threading.Thread (target=wash_clothes

Args= (1, "ape says python"), # args passes tuples and can pass multiple data at the same time

Kwargs= {"a": 1, "b": False}) # kwargs pass dictionary, which can pass multiple key-value pairs at the same time

T2 = threading.Thread (target=clean_room

Args= (2 false), # args passes tuples and can pass multiple data at the same time

Kwargs= {"c": 0.2, "d": False}) # kwargs pass dictionary, which can pass multiple key-value pairs at the same time

T1.start ()

T2.start ()

four。 Thread end

What's worth thinking about is: how many threads are there in the above code? Not two, a total of three threads:

Thread 1: _ _ name__ = = "_ _ main__" as the main thread

Thread 2: T1 as a child thread

Thread 3: T2 as a child thread

Note: the main program will wait for all subroutines to finish.

five。 Introduction of correlation function

1.threading.Thread ()-create and initialize the thread, passing parameters to the thread

2.threading.enumerate ()-returns a list containing the running thread

3.threading.activeCount (): returns the number of running threads, with the same result as len (threading.enumerate ())

4.Thread.start ()-starts the thread

5.Thread.join ()-blocks the function until the thread ends

6.Thread.isAlive ()-returns whether the thread is active

7.Thread.getName ()-returns the thread name

8.Thread.setName ()-sets the thread name

9.Thread.setDaemon ()-set to background thread, where the default is False. If set to True, the main thread will no longer wait for the child thread to finish, but the end of the main thread means the program exits and the child thread ends immediately. Note that the call must be set before start ().

Simple sample code:

one

two

three

four

five

six

seven

eight

nine

ten

eleven

twelve

thirteen

fourteen

fifteen

sixteen

seventeen

eighteen

nineteen

twenty

twenty-one

twenty-two

twenty-three

twenty-four

twenty-five

twenty-six

twenty-seven

twenty-eight

twenty-nine

thirty

thirty-one

thirty-two

thirty-three

thirty-four

thirty-five

thirty-six

thirty-seven

thirty-eight

thirty-nine

forty

forty-one

# Import thread threading module

Import threading

# Import built-in module time

Import time

Def wash_clothes (* args,**kargcs):

Time.sleep (2)

Print ("wash_clothes:", args)

Time.sleep (2)

Print ("wash_clothes:", kargcs)

Def clean_room (* args,**kargcs):

Time.sleep (2)

Print ("clean_room:", args)

Time.sleep (2)

Print ("clean_room:", kargcs)

If _ name__ = = "_ _ main__":

T1 = threading.Thread (target=wash_clothes

Args= (1, "ape says python"), # args passes tuples and can pass multiple data at the same time

Kwargs= {"a": 1, "b": False}) # kwargs pass dictionary, which can pass multiple key-value pairs at the same time

T2 = threading.Thread (target=clean_room

Args= (2 false), # args passes tuples and can pass multiple data at the same time

Kwargs= {"c": 0.2, "d": False}) # kwargs pass dictionary, which can pass multiple key-value pairs at the same time

# setDaemon (True) means that the main thread exits, and no matter which line the child thread executes, the child thread ends automatically

# t1.setDaemon (True)

# t2.setDaemon (True)

T1.start ()

T2.start ()

Print ("threading.enumerate ():", threading.enumerate ())

Print ("threading.activeCount ():", threading.activeCount ())

Print ("t1.isAlive ():", t1.isAlive ())

Print ("t1.getName ():", t1.getName ())

Print ("t2.isAlive ():", t2.isAlive ())

T2.setName ("my_custom_thread_2")

Print ("t2.getName ():", t2.getName ())

Output result:

one

two

three

four

five

six

seven

eight

nine

ten

Threading.enumerate (): [,]

Threading.activeCount (): 3

T1.isAlive (): True

T1.getName (): Thread-1

T2.isAlive (): True

T2.getName (): my_custom_thread_2

Clean_room: (2, False)

Wash_clothes: (1, 'the ape says python')

Wash_clothes: {'averse: 1,' baked: False}

Clean_room: {'clocked: 0.2,' dumped: False}

This is the end of the article on "how to create and pass parameters on python threads". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report