thread/threading
thread/threading
- python内建模块线程练习
thread
1. EXP1, thread简单调用
2. EXP2, thread加入锁
threading
1. EXP1, threading 通过Threading.Thread构造线程
2. EXP2, threading 通过从 Thread 继承,并重写 run() 构造线程
thread
- 简单的线程
1. EXP1, thread简单调用
#!/usr/bin/python# -*- coding: UTF-8 -*-import threadimport time# 为线程定义一个函数def threadTest(threadName):print "%s" %(threadName)# 创建两个线程try:thread.start_new_thread( threadTest, ("Thread-1",) )time.sleep(0.3)thread.start_new_thread( threadTest, ("Thread-2",) )time.sleep(0.3)except:print "Error: unable to start thread"
2. EXP2, thread加入锁
- 起10个进程;
- 单线程独占资源;
- 用锁来保证每个线程结束后再执行下一个进程;
#!/usr/bin/python# -*- coding: UTF-8 -*-import thread, time, randomcount = 0lock = thread.allocate_lock() #创建一个琐对象def threadTest():global count, lockprint lock.acquire() #获取琐for i in xrange(10000):count += 1print lock.release() #释放琐#print thread.exit ()for i in xrange(10):thread.start_new_thread(threadTest, ())time.sleep(0.3)print count
threading
- threading通过对thread模块进行二次封装,提供了更方便的API来操作线程
1. EXP1, threading 通过Threading.Thread构造线程
# encoding: UTF-8# author:sxqimport threading,time,random# 方法1:将要执行的方法作为参数传给Threading.Thread的构造方法count = 0lock = threading.Lock()def func():global countglobal locklock.acquire()print 'func() passed to Thread'for i in xrange(10000):#print countcount += 1lock.release()for i in range(5):t = threading.Thread(target = func, args = (), name = 'thread-' + str(i)).start()print counttime.sleep(3)print countprint type(t)
2. EXP2, threading 通过从 Thread 继承,并重写 run() 构造线程
# encoding: UTF-8# author:sxqimport threading,time,random# 方法2:从Thread继承,并重写run()count = 0lock = threading.Lock()class MyThread(threading.Thread):def run(self):global countglobal lockprint 'pass'lock.acquire()for i in xrange(10000):count += 1lock.release()for i in range(5):MyThread().start()time.sleep(3)print count

浙公网安备 33010602011771号