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 thread
import 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, random
count = 0
lock = thread.allocate_lock() #创建一个琐对象
def threadTest():
global count, lock
print lock.acquire() #获取琐
for i in xrange(10000):
count += 1
print 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:sxq
import threading,time,random
# 方法1:将要执行的方法作为参数传给Threading.Thread的构造方法
count = 0
lock = threading.Lock()
def func():
global count
global lock
lock.acquire()
print 'func() passed to Thread'
for i in xrange(10000):
#print count
count += 1
lock.release()
for i in range(5):
t = threading.Thread(target = func, args = (), name = 'thread-' + str(i)).start()
print count
time.sleep(3)
print count
print type(t)
2. EXP2, threading 通过从 Thread 继承,并重写 run() 构造线程
# encoding: UTF-8
# author:sxq
import threading,time,random
# 方法2:从Thread继承,并重写run()
count = 0
lock = threading.Lock()
class MyThread(threading.Thread):
def run(self):
global count
global lock
print 'pass'
lock.acquire()
for i in xrange(10000):
count += 1
lock.release()
for i in range(5):
MyThread().start()
time.sleep(3)
print count