环境情况如下:
python-2.5.2
Python在文本处理方面很有特色,
演示一下子线程的使用,以后可以用在文本处理中。
python代码(asleep1.py):
变形(asleep2.py):
再变形(asleep3.py):
ansleep1.py是一种简单风格的方式,
ansleep2.py是标准面向对象的方式,java风格
ansleep3.py使用了更灵活的调用方法,对象只存数据,主要逻辑在函数中。
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使用了更灵活的调用方法,对象只存数据,主要逻辑在函数中。