文本处理学习笔记4

环境情况如下:
python-2.5.2

Python在文本处理方面很有特色,
演示一下子线程的使用,以后可以用在文本处理中。

python代码(asleep1.py):

# coding:gbk

import time
import threading

def loop(nloop, nsec):
global count, mutex
print "loop", nloop, time.ctime()
for i in range(nsec):
mutex.acquire()
time.sleep(1)
count = count + 1
print "loop", nloop, count
mutex.release()
print "loop", nloop, time.ctime()

if __name__ == "__main__":
print "main begin", time.ctime()

global count, mutex
count = 0
mutex = threading.Lock()
threads = []

loops = [5, 3]
nloops = range(len(loops))
for i in nloops:
t = threading.Thread(target=loop, args=(i, loops[i]))
threads.append(t)

for i in nloops:
threads[i].start()

for i in nloops:
threads[i].join()

print "main end", time.ctime()

变形(asleep2.py):
# coding:gbk

import time
import threading

class MyThread(threading.Thread):
def __init__(self, args):
threading.Thread.__init__(self)
self.args = args
self.count = 0
def run(self):
self.loop(*self.args)
def loop(self, nloop, nsec):
print "loop", nloop, time.ctime()
t = 0
for i in range(nsec):
time.sleep(1)
t = t + 1
print "loop", nloop, t
self.count = t
print "loop", nloop, time.ctime()

if __name__ == "__main__":
print "main begin", time.ctime()

threads = []
loops = [5, 3]
nloops = range(len(loops))

for i in nloops:
t = MyThread((i, loops[i]))
threads.append(t)

for i in nloops:
threads[i].start()

for i in nloops:
threads[i].join()

mainCount = 0
for i in nloops:
mainCount = mainCount + threads[i].count
print i, threads[i].count
print "main", mainCount

print "main end", time.ctime()

再变形(asleep3.py):
# coding:gbk

import time
import threading

class MyThread(threading.Thread):
def __init__(self, args):
threading.Thread.__init__(self)
self.args = args
self.count = 0
def run(self):
self.count = loop(*self.args)

def loop(nloop, nsec):
print "loop", nloop, time.ctime()
t = 0
for i in range(nsec):
time.sleep(1)
t = t + 1
print "loop", nloop, t
print "loop", nloop, time.ctime()
return t

if __name__ == "__main__":
print "main begin", time.ctime()

threads = []
loops = [5, 3]
nloops = range(len(loops))

for i in nloops:
t = MyThread((i, loops[i]))
threads.append(t)

for i in nloops:
threads[i].start()

for i in nloops:
threads[i].join()

mainCount = 0
for i in nloops:
mainCount = mainCount + threads[i].count
print i, threads[i].count
print "main", mainCount

print "main end", time.ctime()

ansleep1.py是一种简单风格的方式,
ansleep2.py是标准面向对象的方式,java风格
ansleep3.py使用了更灵活的调用方法,对象只存数据,主要逻辑在函数中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值