Python多线程编程简单介绍

yipeiwu_com5年前Python基础

创建线程

格式如下

复制代码 代码如下:

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

这个构造器必须用关键字传参调用
- group 线程组
- target 执行方法
- name 线程名字
- args target执行的元组参数
- kwargs target执行的字典参数

Thread对象函数

函数 描述
start() 开始线程的执行
run() 定义线程的功能的函数(一般会被子类重写)
join(timeout=None) 程序挂起,直到线程结束;如果给了 timeout,则最多阻塞 timeout 秒
getName() 返回线程的名字
setName(name) 设置线程的名字
isAlive() 布尔标志,表示这个线程是否还在运行中
isDaemon() 返回线程的 daemon 标志
setDaemon(daemonic) 把线程的 daemon 标志设为 daemonic(一定要在调用 start()函数前调用)

常用示例

格式

复制代码 代码如下:

import threading

def run(*arg, **karg):
    pass
thread = threading.Thread(target = run, name = "default", args = (), kwargs = {})
thread.start()


实例
复制代码 代码如下:

#!/usr/bin/python
#coding=utf-8

import threading
from time import ctime,sleep

def sing(*arg):
    print "sing start: ", arg
    sleep(1)
    print "sing stop"


def dance(*arg):
    print "dance start: ", arg
    sleep(1)
    print "dance stop"

threads = []

#创建线程对象
t1 = threading.Thread(target = sing, name = 'singThread', args = ('raise me up',))
threads.append(t1)

t2 = threading.Thread(target = dance, name = 'danceThread', args = ('Rup',))
threads.append(t2)

#开始线程
t1.start()
t2.start()

#等待线程结束
for t in threads:
    t.join()

print "game over"


输出
复制代码 代码如下:

sing start:  ('raise me up',)
dance start:  ('Rup',)
sing stop
dance stop
game over

相关文章

浅谈Python类的__getitem__和__setitem__特殊方法

一个有点绕的例子,用PyScripter调试器步进跟踪可以看清楚对 象结构的具体细节。 对原作改变了一下,在未定义子对象属性时__getitem__中使用现成的__setitem__来定...

python中模块查找的原理与方法详解

前言 本文主要给大家介绍了关于python模块查找的原理与方式,分享出来供大家参考学习,下面话不多说,来一起看看详细的介绍: 基础概念 module 模块, 一个 py 文件或以其他文...

tensorflow入门之训练简单的神经网络方法

这几天开始学tensorflow,先来做一下学习记录 一.神经网络解决问题步骤: 1.提取问题中实体的特征向量作为神经网络的输入。也就是说要对数据集进行特征工程,然后知道每个样本...

Python 实现遥感影像波段组合的示例代码

Python 实现遥感影像波段组合的示例代码

最近要做个遥感相关的小系统,需要波段组合功能,网上找了可以使用ArcGIS安装时自带的arcpy包,但是Python3.7不能使用现有ArcGIS10.2版本,也不想再装其他版本,所以只...

python中的内置函数getattr()介绍及示例

在python的官方文档中:getattr()的解释如下: getattr(object, name[, default]) Return the value of the nam...