python学习之5 多线程threading
2016-01-20 20:48
447 查看
python学习之5 多线程threading
模块
python自带两个模块,为thread和threading。常用的为threading模块。
threading模块
Thread 线程类,这是我们用的最多的一个类,你可以指定线程函数执行或者继承自它都可以实现子线程功能;Timer与Thread类似,但要等待一段时间后才开始运行;
Lock 锁原语,这个我们可以对全局变量互斥时使用;
RLock 可重入锁,使单线程可以再次获得已经获得的锁;
Condition 条件变量,能让一个线程停下来,等待其他线程满足某个“条件”;
Event 通用的条件变量。多个线程可以等待某个事件发生,在事件发生后,所有的线程都被激活;
Semaphore为等待锁的线程提供一个类似“等候室”的结构;
BoundedSemaphore 与semaphore类似,但不允许超过初始值;
Queue:实现了多生产者(Producer)、多消费者(Consumer)的队列,支持锁原语,能够在多个线程之间提供很好的同步支持。
其中Thread类
是你主要的线程类,可以创建进程实例。该类提供的函数包括:getName(self) 返回线程的名字
isAlive(self) 布尔标志,表示这个线程是否还在运行中
isDaemon(self) 返回线程的daemon标志
join(self, timeout=None) 程序挂起,直到线程结束,如果给出timeout,则最多阻塞timeout秒
run(self) 定义线程的功能函数
setDaemon(self, daemonic) 把线程的daemon标志设为daemonic
setName(self, name) 设置线程的名字
start(self) 开始线程执行
练习源码
[code]# coding = utf-8 ######################### # #coding by 刘云飞 ######################### import threading as th from time import ctime, sleep counter = 0 mutex = th.Lock() class MyThread(th.Thread): def __init__(self): th.Thread.__init__(self) def run(self): global counter, mutex sleep(1) if mutex.acquire(): counter += 1 print('this is ', self.name, ',counter is ', counter) mutex.release() if __name__ == '__main__': for i in range(100): ths = MyThread() ths.start()
相关文章推荐
- Pythonic解析
- 深刻理解Python中的元类(metaclass)
- python八荣八耻
- python UnicodeDecodeError: 'ascii' codec can't decode byte 0xa6 in position 907: ordinal not in range(128)
- Python中使用urllib2模块编写爬虫的简单上手示例
- Python字符串与数字互转,数字格式化
- Python 快速入门(上) - 基本语法
- python读取配置文件
- 转载:Python 包管理工具解惑
- graphite 安装
- Python copy对象(copy与deepcopy)
- python 多线程 thread
- Python程序的执行原理
- Python动态监控日志的内容
- Python算法题----取出最长回文子串
- Python进程监控-MyProcMonitor
- python新的开始
- kafka-python安装
- Python同时向控制台和文件输出日志logging的方法 Python logging模块详解
- 《Python for kids》学习笔记(三)