python 多进程和多线程
2015-02-13 18:25
399 查看
多进程和多线程
#!/usr/bin/python # -*- coding:utf-8 -*- import os import threading import multiprocessing import time #Process entry def process_worker(sign,lock,function): global count_process #lock.acquire() count_process += 1 print(sign, os.getpid()) print apply(function) #lock.release() #Thread entry def thread_worker(sign, lock,function): global count_thread lock.acquire() count_thread += 1 print(sign, os.getpid()) print apply(function) lock.release() #real work functions def Lee(): return 'I am Lee' def Marlon(): return 'I am Marlon' def Allen(): return 'I am Allen' count_thread = 0 count_process = 0 if __name__=='__main__': # Multi-process begin multiprocessing.freeze_support() #window python 中需要,否则会出现随意打开很多进程的情况 print('Main:',os.getpid()) record = [] lock = multiprocessing.Lock() func_list = [Lee,Marlon,Allen] for function in func_list: process = multiprocessing.Process(target=process_worker,args=('Process',lock,function)) process.start() record.append(process) for process in record: process.join() print "count_process value is", count_process #该值没有改变,多进程不共享内存 # Multi-thread begin record = [] lock = threading.Lock() for function in func_list: thread = threading.Thread(target=thread_worker,args=('thread',lock,function)) thread.start() record.append(thread) for thread in record: thread.join() print "count_thread value is", count_thread #该值改变,所以多线程共享内存
相关文章推荐
- Python串行运算、并行运算、多线程、多进程对比实验
- Python守护进程(多线程开发)
- 04 Python正则表达式 爬虫程序 变量的引用,浅拷贝,深拷贝 多线程 进程锁 数据库模块
- python学习笔记(4)-进程和线程(二)-多线程
- Python的多线程和多进程模块对比测试
- python 实现多进程和多线程的例子
- python的多线程、多进程代码示例
- 3.python学习笔记:python下的多进程与多线程(一)
- Python中的GIL、多进程和多线程
- python的多线程和多进程
- 14-08-07 关于程序、进程、线程,以及python中实现多线程的办法
- python 多进程并发与多线程并发总结
- python 多线程和多进程
- Python多线程/进程:os、sys、Queue、multiprocessing、threading
- python 多线程和多进程的区别 mutiprocessing theading
- 学习python多线程和多进程的一点感想
- Python串行运算、并行运算、多线程、多进程对比实验
- Python的多线程与多进程实践
- Python多线程、异步+多进程爬虫实现代码
- 为什么在Python里推荐使用多进程而不是多线程?