您的位置:首页 > 编程语言 > Python开发

python 多线程和多进程

2015-04-17 17:22 393 查看
在python中,多线程的使用还是比较多的,记录一下class继承的实现方法

多线程

class mythread(threading.Thread):
def __init__(self,i):
threading.Thread.__init__(self)
self.i = i
def run(self):
for j in range(10000):
print self.i

if __name__ == '__main__':
threads = []
for i in range(5):
t = mythread(i)
t.start()
if threading.activeCount()>2:#让线程数不大于2
for t in threads:
t.join()
for t in thread:
t.join()


当然,可以使用lock=threading.RLock() #需要的话使用这个进行锁,lock.acquire()与lock.release()包住次只允许一个线程操作的地方。多线程有些时候不能提高程序的执行效率,主要限制为python的机制GIL将线程有效地限制到一个核中。详细http://www.cnblogs.com/mindsbook/archive/2009/10/15/thread-safety-and-GIL.html

多进程

import multiprocessing
class proc(multiprocessing.Process):
def __init__(self,i):
multiprocessing.Process.__init__(self)
self.t = i
def run(self):
for i in range(10000):
print self.t,
if __name__ == '__main__':
jobs = []
for i in range(7):
p = proc(i)
p.start()
jobs.append(p)
print multiprocessing.active_children()
if len(multiprocessing.active_children())>1:
for j in jobs:
j.join()
for j in jobs:
j.join()
print "over"




import threading
import Queue
class procg(threading.Thread):
def __init__(self,queue,lockname,i):
threading.Thread.__init__(self)
self.queue = queue
self.lock = lockname
self.num = i
def run(self):
import time
i = 0
while(i<500):
self.lock.acquire()
if not self.queue.empty():
data = self.queue.get()
print 'get '+ self.num +': '+str(data)
self.lock.release()
for j in range(100000):
i = i
i += 1
else:
self.lock.release()

class proc(threading.Thread):
def __init__(self,queue,lockname):
threading.Thread.__init__(self)
self.queue = queue
self.lock = lockname
def run(self):
import time
i = 0
while(i<1000):
self.lock.acquire()
self.queue.put(i)
print "put " + str(i)
self.lock.release()
for j in range(100000):
i = i
i += 1

if __name__ == '__main__':
jobs = []
queue = Queue.Queue()
queueLock = threading.Lock()
p = proc(queue,queueLock)
p.start()
jobs.append(p)
g1 = procg(queue,queueLock,'1')
g1.start()
jobs.append(g1)
g2 = procg(queue,queueLock,'2')
g2.start()
jobs.append(g2)
for j in jobs:
j.join()
print "over"


详情参考 http://outofmemory.cn/code-snippet/2267/Python-duojincheng-multiprocessing-usage-examplehttp://bofang.iteye.com/blog/1684345
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  python 多线程 多进程