[Python]多线程入门
原文:http://blog.csdn.net/ice110956/article/details/28421807
Python的多线程有两种实现方法:
函数,线程类
1.函数
调用thread模块中的start_new_thread()函数来创建线程,以线程函数的形式告诉线程该做什么
- # -*- coding: utf-8 -*-
- import thread
- def f(name):
- #定义线程函数
- print "this is " + name
- if __name__ == '__main__':
- thread.start_new_thread(f, ("thread1",))
- #用start_new_thread()调用线程函数和其他参数
- while 1:
- pass
不过这种方法暂时没能找到其他辅助方法,连主线程等待都要用while 1这种方法解决。
2.线程类
调用threading模块,创建threading.Thread的子类来得到自定义线程类。
- # -*- coding: utf-8 -*-
- import threading
- class Th(threading.Thread):
- def __init__(self, name):
- threading.Thread.__init__(self)
- self.t_name = name
- #调用父类构造函数
- def run(self):
- #重写run()函数,线程默认从此函数开始执行
- print "This is " + self.t_name
- if __name__ == '__main__':
- thread1 = Th("Thread_1")
- thread1.start()
- #start()函数启动线程,自动执行run()函数
threading.Thread类的可继承函数:
getName() 获得线程对象名称
setName() 设置线程对象名称
join() 等待调用的线程结束后再运行之后的命令
setDaemon(bool) 阻塞模式,True:父线程不等待子线程结束,False 等待,默认为False
isDaemon() 判断子线程是否和父线程一起结束,即setDaemon()设置的值
isAlive() 判断线程是否在运行
实例
- import threading
- import time
- class Th(threading.Thread):
- def __init__(self, thread_name):
- threading.Thread.__init__(self)
- self.setName(thread_name)
- def run(self):
- print "This is thread " + self.getName()
- for i in range(5):
- time.sleep(1)
- print str(i)
- print self.getName() + "is over"
join()阻塞等待
- if __name__ == '__main__':
- thread1 = Th("T1 ")
- thread1.start()
- #thread1.join()
- print "main thread is over"
不带thread1.join(),得到如下结果:
This is thread T1
main thread is over
0
1
2
T1 is over
不等待thread1完成,执行之后语句。
加了thread1.join(),得到如下结果:
This is thread T1
0
1
2
T1 is over
main thread is over
阻塞等待thread1结束,才执行下面语句
主线程等待
- if __name__ == '__main__':
- thread1 = Th("T1 ")
- thread1.setDaemon(True)
- #要在线程执行之前就设置这个量
- thread1.start()
- print "main thread is over"
报错:Exception in thread T1 (most likely raised during interpreter shutdown):
也就是主线程不等待子线程就结束了。
多个子线程
- if __name__ == '__main__':
- for i in range(3):
- t = Th(str(i))
- t.start()
- print "main thread is over"
这里的t可同时处理多个线程,即t为线程句柄,重新赋值不影响线程。
这里奇怪的是,运行t.run()时,不会再执行其他线程。虽不明,还是用start()吧。暂且理解为start()是非阻塞并行的,而run是阻塞的。
线程锁
threading提供线程锁,可以实现线程同步。
- import threading
- import time
- class Th(threading.Thread):
- def __init__(self, thread_name):
- threading.Thread.__init__(self)
- self.setName(thread_name)
- def run(self):
- threadLock.acquire()
- #获得锁之后再运行
- print "This is thread " + self.getName()
- for i in range(3):
- time.sleep(1)
- print str(i)
- print self.getName() + " is over"
- threadLock.release()
- #释放锁
- if __name__ == '__main__':
- threadLock = threading.Lock()
- #设置全局锁
- thread1 = Th('Thread_1')
- thread2 = Th('Thread_2')
- thread1.start()
- thread2.start()
得到结果:
This is thread Thread_1
0
1
2
Thread_1 is over
This is thread Thread_2
0
1
2
Thread_2 is over
[Python]多线程入门的更多相关文章
- thread/threading——Python多线程入门笔记
1 什么是线程? (1)线程不同于程序. 线程不能够独立执行,必须依存在应用程序中,由应用程序提供多个线程执行控制: 多线程类似于同时执行多个不同程序. (2)线程不同于进程. 每个独立的进程有一个程 ...
- python爬虫入门八:多进程/多线程
什么是多线程/多进程 引用虫师的解释: 计算机程序只不过是磁盘中可执行的,二进制(或其它类型)的数据.它们只有在被读取到内存中,被操作系统调用的时候才开始它们的生命期. 进程(有时被称为重量级进程)是 ...
- Python基础入门教程
Python基础入门教程 Python基础教程 Python 简介 Python环境搭建 Python 基础语法 Python 变量类型 Python 运算符 Python 条件语句 Python 循 ...
- day-3 python多线程编程知识点汇总
python语言以容易入门,适合应用开发,编程简洁,第三方库多等等诸多优点,并吸引广大编程爱好者.但是也存在一个被熟知的性能瓶颈:python解释器引入GIL锁以后,多CPU场景下,也不再是并行方式运 ...
- Python 爬虫入门(二)——爬取妹子图
Python 爬虫入门 听说你写代码没动力?本文就给你动力,爬取妹子图.如果这也没动力那就没救了. GitHub 地址: https://github.com/injetlee/Python/blob ...
- Python 爬虫入门之爬取妹子图
Python 爬虫入门之爬取妹子图 来源:李英杰 链接: https://segmentfault.com/a/1190000015798452 听说你写代码没动力?本文就给你动力,爬取妹子图.如果 ...
- python线程入门
目录 python线程入门 线程与进程 线程 总结 参考 python线程入门 正常情况下,我们在启动一个程序的时候.这个程序会先启动一个进程,启动之后这个进程会启动起来一个线程.这个线程再去处理事务 ...
- Python多线程问题的资料查找与汇总
Python多线程问题的资料查找与汇总 声明: 1)本报告由博客园bitpeach撰写,版权所有,免费转载,请注明出处,并请勿作商业用途. 2)若本文档内有侵权文字或图片等内容,请联系作者bitpea ...
- python多线程爬取世纪佳缘女生资料并简单数据分析
一. 目标 作为一只万年单身狗,一直很好奇女生找对象的时候都在想啥呢,这事也不好意思直接问身边的女生,不然别人还以为你要跟她表白啥的,况且工科出身的自己本来接触的女生就少,即使是挨个问遍,样本量也 ...
随机推荐
- HDU 4788 Hard Disk Drive (2013成都H,水题)
Hard Disk Drive Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)T ...
- LPC-LINK 2
LPC-Link 2 is an extensible, stand-alone debug adapter that can be configured to support various dev ...
- Renesas M16C/6X -- Simple PWM Signal Generation Using DMA
1. Requirements To generate a PWM output, we need to create a train of pulses with constant period a ...
- ST推出新软件STM32Cube ,让STM32微控制器应用设计变得更容易、更快、更好用
功能强大的STM32Cube 新软件平台由设计工具.中间件和硬件抽象层组成,让客户能够集中精力创新 意法半导体(STMicroelectronics,简称ST)针对STM32微控制器推出一套免费的功能 ...
- [Go] 命令行参数解析包(flag 包)使用详解
Go 的 flag 包可以解析命令行的参数. 一.命令行语法 命令行语法主要有以下几种形式: cmd -flag // 只支持bool类型 cmd -flag=xxx cmd -flag ...
- 推荐一个文献翻译软件--Deja Vu X
首先我的这篇博客推荐的软件并非你觉得翻译精确度有多高的软件,假设是这种话就不用往下看了,免得浪费时间,仅仅是一个对于翻译文献非常方便的工具,方面在哪请看下文. 我是不会告诉你凡事用过这个软件的人都说好 ...
- 恶意软件正在利用SSLserver窃取用户个人信息!
安全套接层协议(SSL)及安全传输层协议(TLS)旨在提供一个安全.加密的client和server之间的连接网络.为进一步进行身份验证和加密,server必须提供证书,从而直接有效地证明其身份. 使 ...
- 解决ubuntu上在androidstudio中启动emulator闪退的问题(2)
平台 Ubuntu14.04 64 现象 在AndrodStudio中点击模拟器的启动按钮后,模拟器界面弹出后,又立刻闪退. 解决 一.查看模拟器的信息 从上面可以看到模拟器的存放路径以及名称: 路径 ...
- IIS7.5标识介绍
应用程序池的标识是运行应用程序池的工作进程所使用的服务帐户名称.默认情况下,应用程序池以 Network Service 用户帐户运行,该帐户拥有低级别的用户权限.您可以将应用程序池配置为以 Wind ...
- python测试开发django-22.admin首页和title修改
前言 django的admin首页默认显示的"Django 管理",title显示的是"Django 站点管理员",这里的文案内容可以修改成自己项目的后台页面内 ...