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求两个圆的交点坐标或三个圆的交点坐标方法

计算两个圆的交点 代码如下: # -*- coding: utf-8 -*- import math import numpy as np def insec(p1,r1,p2,r2...

Python开发之基于模板匹配的信用卡数字识别功能

Python开发之基于模板匹配的信用卡数字识别功能

环境介绍 Python 3.6 + OpenCV 3.4.1.15 原理介绍 首先,提取出模板中每一个数字的轮廓,再对信用卡图像进行处理,提取其中的数字部分,将该部分数字与模板进行匹...

Python中的十大图像处理工具(小结)

Python中的十大图像处理工具(小结)

Python之成为图像处理任务的最佳选择,是因为这一科学编程语言日益普及,并且其自身免费提供许多最先进的图像处理工具。本文主要介绍了一些简单易懂最常用的Python图像处理库。 当今世界...

浅谈Python中函数的参数传递

1.普通的参数传递 >>> def add(a,b): return a+b >>> print add(1,2) 3 >&g...

Python中的两个内置模块介绍

使用了Python一段时间后,可以说Python的基本单位就是模块了,在使用模块的时候我们一般会使用通过import语句来将其导入,但是我们在没有导入任何模块的时候,我们却能使用这样的一...