欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

python模块_Python模块

程序员文章站 2022-03-05 13:45:48
...

python模块

Python中的threading模块 (threading Module In Python)

As we have seen in the previous tutorial, threading module is used for creating, controlling and managing threads in python. In this tutorial, we will discuss about various functions and object types defined by the threading module.

正如我们在上一教程中所看到的那样threading模块用于在python中创建,控制和管理线程。 在本教程中,我们将讨论threading模块定义的各种函数和对象类型。

threading模块功能 (threading Module Functions)

This module provides the following functions for managing threads:

该模块提供以下用于管理线程的功能:

Here is the code snippet from last tutorial, we will be using this to see the various functions provided by the threading module in action.

这是上一教程的代码片段,我们将使用它来查看threading模块在运行中提供的各种功能。



穿线。 active_count()函数 (threading.active_count() Function)

This function returns the number of Thread objects currently alive.

此函数返回当前活动的Thread对象的数量。

import time
import threading

def thread1(i):
    time.sleep(3)
    #print('No. printed by Thread 1: %d' %i)

def thread2(i):
    time.sleep(3)
    #print('No. printed by Thread 2: %d' %i)

if __name__ == '__main__':
    t1 = threading.Thread(target=thread1, args=(10,))
    t2 = threading.Thread(target=thread2, args=(12,))
    t1.start()
    t2.start()
    print("No. of active threads: " + threading.active_count())
    t1.join()
    t2.join()

No. of active threads: 3

活动线程数:3

Try running the this code in the terminal above. You will see the number of thread count to be 3, because we have created 2 threads and there in the main thread in which the complete execution is taking place.

尝试在上面的终端中运行此代码。 您将看到线程数为3 ,因为我们已经创建了2个线程,并且在主线程中已在其中执行完整的执行。

穿线。 current_thread() (threading.current_thread())

This function will return the current Thread object, corresponding to the caller's thread of control(which is in the control of caller currently). If the caller's thread of control was not created through the threading module(for example the main thread), then a dummy thread object with limited functionality is returned.

此函数将返回当前的Thread对象,该对象对应于调用者的控制线程(当前位于调用者的控件中)。 如果调用方的控制线程不是通过线程模块(例如线程)创建的,则返回功能有限的虚拟线程对象。

import time
import threading

def thread1(i):
    time.sleep(3)
    #print('No. printed by Thread 1: %d' %i)

def thread2(i):
    time.sleep(3)
    #print('No. printed by Thread 2: %d' %i)

if __name__ == '__main__':
    t1 = threading.Thread(target=thread1, args=(10,))
    t2 = threading.Thread(target=thread2, args=(12,))
    t1.start()
    t2.start()
    print("Current thread is: " + threading.current_thread())
    t1.join()
    t2.join()

Current thread is: <_mainthread started>

当前线程是:<_mainthread启动>

穿线。 get_ident() (threading.get_ident())

This function returns the thread identifier of the current thread. This is a nonzero integer value. If we started the thread, then this method will return its identifier, otherwise, it will return None.

该函数返回当前线程的线程标识符 。 这是一个非零的整数值。 如果我们启动线程,则此方法将返回其标识符,否则,将返回None

We can use this method to index a dictionary of thread-specific data. Thread identifiers may be recycled when a thread exits(stops) and another thread is created.

我们可以使用此方法为线程专用数据字典建立索引。 当一个线程退出(停止)并创建另一个线程时,线程标识符可以被回收。

threading.get_ident()

140578859194112

140578859194112

穿线。 enumerate() (threading.enumerate())

This method returns a list of all Thread objects currently alive. The list includes daemonic threads(when the program quits, all the daemon threads associated with it are killed automatically), dummy thread objects created by the current thread, and the main thread.

此方法返回当前活动的所有Thread对象的列表。 该列表包括守护程序线程(程序退出时,与其关联的所有守护程序线程都会自动终止 ),由当前线程创建的虚拟线程对象和线程。

Terminated threads and threads that have not yet been started are not present in this list.

终止线程和尚未启动的线程不在此列表中。

threading.enumerate()

[<_MainThread(MainThread, started 139890175817472)>, <Thread(Thread-1, started 139890151225088)>, <Thread(Thread-2, started 139890142832384)>]

[<_MainThread(MainThread,开始139890175817472)>,<Thread(Thread-1,开始139890151225088)>,<Thread(Thread-2,开始139890142832384)>]

穿线。 main_thread() (threading.main_thread())

This method returns the main Thread object. In normal conditions, the main thread is the thread from which the python interpreter was started.

此方法返回 Thread对象。 在正常情况下, 线程是启动python解释器的线程。

threading.main_thread()

<_MainThread(MainThread, started 139890175817472)>

<_MainThread(MainThread,开始139890175817472)>

穿线。 settrace(fun) (threading.settrace(fun))

This method is used to set a trace function/hook for all the threads started using the threadingmodule. The trace funtion is passed to sys.settrace() method for each thread, which is attache to the thread before the run() method is called.

此方法用于为使用threading模块启动的所有线程设置跟踪功能/挂钩。 跟踪功能将传递给每个线程的sys.settrace()方法,该函数在调用run()方法之前sys.settrace()到该线程。

The callback function which we want to act as the trace function will receive three arguments, frame (the stack frame from the code being run), event (a string naming the type of notification), and arg (an event-specific value)

我们要用作跟踪函数的回调函数将接收三个参数, frame (正在运行的代码的堆栈帧), event (命名通知类型的字符串)和arg (事件特定的值)

def hello(frame, event, arg):
    print("Hello, I am a trace hook.")
threading.settrace(hello)

Try updating the code in the terminal at the top. Put the hello function outside the main method and the statement threading.settrace(hello) just above the statement where we call the start method for the threads.

尝试在顶部的终端中更新代码。 将hello函数放在main方法之外,将语句threading.settrace(hello)放在语句上方,在该语句我们为线程调用start方法。

穿线。 setprofile(fun) (threading.setprofile(fun))

This method is used to set a profile function for all threads started from the threading module. Just like the trace funtion, profile function is also passed to sys.setprofile() method for each thread, which is attache to the thread before the run() method is called.

此方法用于为从线程模块启动的所有线程设置配置文件功能。 就像跟踪功能一样,配置文件功能也传递给每个线程的sys.setprofile()方法,该函数在调用run()方法之前sys.setprofile()到该线程。

threading.setprofile(hello)

穿线。 stack_size([size]) (threading.stack_size([size]))

This method returns the thread stack size utilised when creating new threads. The size argument is optional and can be used to set the stack size to be used for creating subsequent threads, and must be 0 or a positive integer (D=default value is 0).

此方法返回创建新线程时利用的线程堆栈大小。 size参数是可选的,可用于设置用于创建后续线程的堆栈大小,并且必须为0或正整数(D =默认值为0)。

If changing the thread stack size is unsupported, a RuntimeError is raised.

如果不支持更改线程堆栈大小,则会引发RuntimeError

If the specified stack size is invalid, a ValueError is raised.

如果指定的堆栈大小无效,则会引发ValueError

Currently 32 KiB is the minimum stack size which is supported to provide enough stack space for the interpreter.

当前,支持的最小堆栈大小为32 KiB ,以为解释器提供足够的堆栈空间。

穿线。 TIMEOUT_MAX (threading.TIMEOUT_MAX)

Apart from the above specified functions, the threading module also defines a constant. If you specify a timeout value which is greater than the value of the TIMEOUT_MAX constant, you will get an OverflowError.

除了上述指定功能外, threading模块还定义了一个常量。 如果您指定的超时值大于TIMEOUT_MAX常量的值,则会收到OverflowError

threading模块对象 (threading Module Objects)

Apart from the functions specified above, the threading module also provides many classes whose objects are very useful in creating and managing threads.

除了上面指定的功能外, threading模块还提供了许多类,它们的对象在创建和管理线程中非常有用。

Following are some of the Object types:

以下是一些对象类型:

Object Description
Thread Object that represents a single thread of execution.
Lock Primitive lock object.
RLock RLock or Re-entrant lock object provides ability for a single thread to (re)acquire an already-held lock (recursive locking).
Condition Condition variable object causes one thread to wait until certain "condition" has been satisfied by another thread (such as change in state or some data value)
Event Its a more general version of condition variables, whereby a number of threads can be made to wait for some event to occur and all the threads waiting will only awaken when the event happens.
Semaphore Provides a "counter" of finite resources shared between threads block when none are available.
BoundedSemaphore Similar to a Semaphore but ensures that it never exceeds its initial value.
Timer Similar to Thread, except that it waits for a specified period of time before running.
Barrier Creates a "barrier" at which a specified number of threads must all arrive before they're all allowed to continue.
目的 描述
线 表示单个执行线程的对象。
原始锁对象。
RLock或重入锁对象为单个线程提供了(重新)获取已经持有的锁(递归锁)的能力。
健康)状况 条件变量对象使一个线程等待,直到另一个线程满足某些“条件”(例如状态更改或某些数据值)为止
事件 它是条件变量的更通用版本,其中可以使多个线程等待某个事件发生,并且所有等待的线程仅在事件发生时才唤醒。
信号 当没有可用的线程块之间时,提供有限资源“计数器”。
有界信号量 类似于信号量,但确保它永远不会超过其初始值。
计时器 与线程类似,区别在于线程在运行之前要等待指定的时间。
屏障 创建一个“屏障”,指定数量的线程必须先到达该屏障,然后才能全部继续。

The above table gives a brief introduction of various object types in python threading module. We will discuss about all these objects in details in the next few tutorials.

上表简要介绍了python线程模块中的各种对象类型。 在接下来的几篇教程中,我们将详细讨论所有这些对象。

翻译自: https://www.studytonight.com/python/threading-module-in-python

python模块