Chinaunix首页 | 论坛 | 博客
  • 博客访问: 9140119
  • 博文数量: 1725
  • 博客积分: 12961
  • 博客等级: 上将
  • 技术积分: 19840
  • 用 户 组: 普通用户
  • 注册时间: 2009-01-09 11:25
个人简介

偷得浮生半桶水(半日闲), 好记性不如抄下来(烂笔头). 信息爆炸的时代, 学习是一项持续的工作.

文章分类

全部博文(1725)

文章存档

2024年(1)

2023年(26)

2022年(112)

2021年(217)

2020年(157)

2019年(192)

2018年(81)

2017年(78)

2016年(70)

2015年(52)

2014年(40)

2013年(51)

2012年(85)

2011年(45)

2010年(231)

2009年(287)

分类: Windows平台

2018-01-11 14:50:54

多进程模块:
subprocess 模块, 实现多进程要求。提供了运行其他程序的功能, 可以传递命令行参数, 可以通过管道进行通信。同时也有 spawn函数、os.system()等内容。

sys.executable 代表当前运行的python解释器。
点击(此处)折叠或打开
  1. pipe = subprocess.Popen(cmdline, stdin=subprocess.PIPE)  # cmdline类似 "python3 /code/my.py 参数"
  2. pipes.append(pipe)
  3. pipe.stdin.write(msg_str.encode("utf8" + b"\n") #subprocess模块读写的是字节
  4. pipe.stdin.close()
  5.   
  6.  
  7. while pipes:
  8.   pipe = pipes.pop()
  9.   pipe.wait() # 等待管道的关闭。
  10.  
  11.  
  12. 管道的另外一段子进程可以使用 
  13. stdin = sys.stdin.buffer.read()  
  14. lines = stdin.decode("utf8", "ignore").splitlines() #获得输入的字符串。
  15. 或者用
  16. sys.stdin = sys.stdin.detach()
  17. stdin = sys.stdin.read()
  18. lines = stdin.decode("utf8", "ignore").splitlines() #获得输入的字符串

点击(此处)折叠或打开

  1. 按块读入文件的相关代码

  2. with open(filename, "rb") as fh:
  3.   while True:
  4.     current = fh.read(1024)
  5.     if not current:
  6.        break
  7.     current = current.decode("utf8", "ignore")
|||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
多线程:
引入 threading 模块
http://blog.chinaunix.net/uid-27875-id-5780794.html  多线程的讲义
http://blog.chinaunix.net/uid-27875-id-5780813.html  多线程的类实现以及通信 Queue
创建线程方式:
1. 调用
threading.Thread(target=func,args=(1,)) # 输入函数与元组
2. 创建 
threading.Thread 的子类, 可以重新实现 __init__()方法(此时必须调用积累的实现,即要使用threading.Thread.__init__(self)), 且必须要实现 run()方法, 那么在调用 start()方法是, run会在内部被调用。

线程通信:
queue.Queue类的锁机制是其内部实现的。queue.Queue.join()方法为阻塞, 直到队列为空。

  
    queue.Queue 是 FIFO 机制工作
    queue.LifoQueue: 是 LIFO 后进先出
    queue.PriorityQueue接受二元组(优先级,数据项), 优先级低的最先处理。
所有队列在创建时都可以指定最大容量, 如果队列项目个数已满, 则添加动作会阻塞

Queue的操作为
queue.Queue.get(self, block=True, timeout=None)
queue.Queue.put(self, item, block=True, timeout=None)
在线程内部, 对queue的项目get()完毕后, 调用 queue.Queue.task_done()是必要的

有一个模块multiprocessing, 其中包含了多线程和队列的实现, 线程基类为 multiprocessing.Process, 队列为 multiprocessing.JoinableQueue. 好处是他在多核机器上有更快的运行潜力

锁机制:
lock = threading.Lock()

with lock:
   suite

点击(此处)折叠或打开

  1. md5 = hashlib.md5()
  2. md5.update(数据)
  3. md5.digest()
阅读(2304) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~