python多线程编程(一) 添加线程

参考:

17.1. threading — Thread-based parallelism

一.背景

二.常见类和函数

Ⅰ.函数

因为现在还是最基础的阶段,这里介绍的函数也是最简单的函数,下面几个函数就是查看当前一些线程信息的函数.

threading.active_count()

返回当前活动的线程数量.并且数量是和enumerate() 函数返回的列表长度相同.

threading.current_thread()

返回当前的线程对象.Return the current Thread object, corresponding to the caller’s thread of control. If the caller’s thread of control was not created through the threading module, a dummy thread object with limited functionality is returned.

threading.enumerate()

返回当前所有活动的线程列表,这个列表包括守护线程(daemonic threads) dummy thread objects created by current_thread(), and the main thread.不包括已经终止的线程和未被启动(start)的线程.

用一个例子就能够说明上面几个函数的用法了.

import time
import threading

def main():
    print("active thread num: ",threading.active_count())
    print("activa threads list: ",threading.enumerate())
    print("current activate thread: ",threading.current_thread())

if __name__=="__main__":
    main()

结果:

active thread num:  1
activa threads list:  [<_MainThread(MainThread, started 8960)>]
current activate thread:  <_MainThread(MainThread, started 8960)>

从结果可以看到,这里只有一个活动的线程,那就是主线程.这里写作_MainThread ,我们也没有另外添加新的线程.

熟悉上面的东西之后,我们可以试一下添加新的线程,怎么添加新的线程呢?你得先知道基本的线程类.

Ⅱ.类

最基本的类就是Thread类了.这里列出Thread类的基本使用API.

class threading.Thread(group=None, target=None, name=None, args=(), kwargs={}, *, daemon=None)

构造函数,同时这个构造函数每次使用的时候都应该用关键字参数来使用.

参数,这里直说两个参数,那就是target和name.

target:可调用对象,能够被run()唤醒.
name: 线程名称,默认的是通过“Thread-N”来表示线程名称. 

start()

启动线程,不能够在同一个线程上启动多次.

run()

表示这个线程活动的函数,你可以通过在子类中重写这个函数来改变行为.

join(timeout=None)

等待这个线程结束.一个线程能够调用join() 多次.

name

A string used for identification purposes only. It has no semantics. Multiple threads may be given the same name. The initial name is set by the constructor.

ident
The ‘thread identifier’ of this thread or None if the thread has not been started. This is a nonzero integer. See the get_ident() function. Thread identifiers may be recycled when a thread exits and another thread is created. The identifier is available even after the thread has exited.

is_alive()

返回是否这个线程还活动

This method returns True just before the run() method starts until just after the run() method terminates. The module function enumerate() returns a list of all alive threads.

daemon
A boolean value indicating whether this thread is a daemon thread (True) or not (False). This must be set before start() is called, otherwise RuntimeError is raised. Its initial value is inherited from the creating thread; the main thread is not a daemon thread and therefore all threads created in the main thread default to daemon = False.

The entire Python program exits when no alive non-daemon threads are left.

三.添加一个线程

接下来,我们就能够自己添加一个线程啦.直接给出一个简单例子,然后分析这个例子的运作过程.

import time
import threading

def fun():
    print("this is a thread called function",threading.current_thread())


def main():
    thread_1 = threading.Thread(target=fun, name="thread_1")
    thread_1.start()
    print("active thread num: ", threading.active_count())
    print("activa threads list: ",threading.enumerate())
    print("current activate thread: ",threading.current_thread())
    print("active thread num: ", threading.active_count())

if __name__=="__main__":
    main()

结果:

this is a thread called function <Thread(thread_1, started 6780)>
active thread num:  2
activa threads list:  [<_MainThread(MainThread, started 17360)>]
current activate thread:  <_MainThread(MainThread, started 17360)>
active thread num:  1

这段代码其实就是和最开始输出信息的那段代码差不多,只加了一点东西.首先就是加了一个函数fun(),首先我们知道是,创建新线程的时候,里面需要传进去一个可以调用的对象,这里这个fun()函数就是我们希望新线程希望调用的对象.然后通过创建一个Thread对象来创建新的线程.thread_1 = threading.Thread(target=fun, name="thread_1") 这句话就非常简单的创建了一个线程对象.然后调用这个对象的start() 函数来启动就行了. 就这么多,还是非常简单的.

然后接下来我们分析一下结果.结果的第一句话表示线程启动了,输出了线程调用函数的那句话.然后接下来显示的是现在活动的线程数量是2,但是下面活动线程列表里面只有一个线程.这是因为,执行到print("activa threads list: ",threading.enumerate()) 这句话的时候,新建的线程应该已经终止了.

所以,这里例子简单告诉我们怎么使用线程,同时,也可以看出来,某一些线程的结束时间你是不知道的,这就增加了多线程编程的不确定性.你需要在你的任务中非常仔细的分析各个线程可能发生的情况.

到这里,最基本添加一个线程就介绍完毕了.

猜你喜欢

转载自blog.csdn.net/xierhacker/article/details/79172609
今日推荐