python多进程线程学习_Python 多进程/多线程 学习笔记

【多进程/多线程】

# 多进程和多线程的区别在于,对于同一个变量,多进程是每个进程都有一份自己的拷贝,而多线程则是共享这个变量。

#

多线程使用不当有一定数据风险,应该为此加锁

# 因为 python 解释器带有全局锁 GIL,所以

python 多线程并不能真正实现并发

1)新建一个子进程

# python 提供了跨平台多进程模块 multiprocessing

from multiprocessing import Process

import os

def newProc(name): # 定义子进程要调用的函数

print 'Child process %s is running, PID is %d...' %(name, os.getpid())

if __name__ == '__main__': # 若操作系统是 Windows 必须加上这个判断

print 'Parent process ID is %d' %(os.getpid())

print 'Creating new process...'

proc = Process(target = newProc, args = ('CHINA')) # 创建子进程

proc.start() # 启动子进程

proc.join() # 等待子进程运行完毕之后再继续执行后续代码

print 'new process is done.'2)批量创建子进程

# 模块 multiprocessing 中的 Pool 函数可以实现批量异步创建线程

from multiprocessing import Pool

import os

def childProc(id): # 定义子进程要调用的函数

print 'Child process %d running, PID is %d....' %(id, os.getpid())

if __name__ == '__main__': # 若操作系统是 Windows 必须加上这个判断

print 'Parent process running, PID is %d' %(os.getpid())

print 'Creating 5 processes now...'

proc = Pool()

for i in range(5):

proc.apply_async(childProc, args = (i, )) # 创建子进程

print 'Wating for all child processes done....'

proc.close() # 停止添加新的子进程

proc.join() # 等待所有子进程运行完毕再执行后续代码

print 'All child processes are done.'3)新建线程

# 模块 threading 中的 Thread 函数可以为进程创建线程

import threading

def newThread(): # 定义创建线程中要调用的函数

print 'NewThread now running...' %(threading.current_thread().name)

print 'Parent thread now running...' %(threading.current_thread().name)

thr = threading.Thread(target = newThread, name = 'ChildThread') # 创建线程

thr.start() # 启动线程

thr.join() # 等待线程结束

print 'Child thread is done.'4)为多线程中操作的数据加锁

# 因为多线程操作时有将数据改乱的风险,所以要对数据加锁保障数据安全

# 在处理加锁数据时,代码的执行模式是单线程的

# 模块 threading 中的 Lock 函数可以创建锁

import threading

gScore = 100

threadPool = []

gScoreLock = threading.Lock() # 为数据创建锁

def newThread(): # 定义线程中要调用的函数

gScoreLock.acquire() # 尝试获取锁

try:

global gScore

gScore = gScore / 1

print 'gScore is:', gScore

finally:

gScoreLock.release() # 释放锁

for i in range(30): # 数据不加锁的情况下,线程越多数据被改乱的几率越大

threadPool.append(threading.Thread(target = newThread, name = i)) # 创建线程池

for i in threadPool:

i.start()

for i in threadPool:

i.join()

print 'All threads done.'

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值