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的框架中一些会话程序的管理

 Django, Bottle, Flask,等所有的python web框架都需要配置一个SECRET_KEY。文档通常推荐我们使用随机的值,但我很难发现他有任何文字说明,因...

python 执行shell命令并将结果保存的实例

方法1: 将shell执行的结果保存到字符串 def run_cmd(cmd): result_str='' process = subprocess.Popen(cmd, sh...

Django中使用locals()函数的技巧

对 current_datetime 的一次赋值操作: def current_datetime(request): now = datetime.datetime.now()...

Python中防止sql注入的方法详解

前言 大家应该都知道现在web漏洞之首莫过于sql了,不管使用哪种语言进行web后端开发,只要使用了关系型数据库,可能都会遇到sql注入攻击问题。那么在Python web开发的过程中s...

学习python可以干什么

python是什么? python的中文名称是蟒蛇,是一种计算机程序设计语言;是一种动态的、面向对象的脚本语言。最初是用来编写自动化脚本的,随着版本的不断更新和语言新功能的添加,越来越多...