我們前面提到了進(jìn)程是由若干線程組成的兔魂,一個(gè)進(jìn)程至少有一個(gè)線程栈妆。
多線程優(yōu)點(diǎn):
- 在一個(gè)進(jìn)程中的多線程和主線程分享相同的數(shù)據(jù)空間扛吞,因此可以很容易的分享信息和通信初肉。
- 線程有時(shí)候被稱為輕量級(jí)進(jìn)程酷鸦,并且他們不需要太多的內(nèi)存開銷,比起進(jìn)程更低成本牙咏。
一個(gè)線程都有一個(gè)開始,一個(gè)執(zhí)行序列和一個(gè)結(jié)論臼隔。它有一個(gè)指令指針用在目前運(yùn)行在的上下文中跟蹤。
- 他可以被搶占(中斷)
- 當(dāng)在其他線程運(yùn)行的時(shí)候可以被臨時(shí)掛起
Python的標(biāo)準(zhǔn)庫(kù)提供了兩個(gè)模塊:thread和threading妄壶,thread是低級(jí)模塊摔握,threading是高級(jí)模塊,對(duì)thread進(jìn)行了封裝丁寄。絕大多數(shù)情況下氨淌,我們只需要使用threading這個(gè)高級(jí)模塊。
#!/usr/bin/python
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
print_time(self.name, self.counter, 5)
print "Exiting " + self.name
def print_time(threadName, delay, counter):
while counter:
if exitFlag:
threadName.exit()
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
# Create new threads
thread1 = myThread(1, "Thread-1", 1)
thread2 = myThread(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
print "Exiting Main Thread"
運(yùn)行結(jié)果:
Starting Thread-1
Starting Thread-2
Exiting Main Thread
Thread-1: Thu Mar 21 09:10:03 2013
Thread-1: Thu Mar 21 09:10:04 2013
Thread-2: Thu Mar 21 09:10:04 2013
Thread-1: Thu Mar 21 09:10:05 2013
Thread-1: Thu Mar 21 09:10:06 2013
Thread-2: Thu Mar 21 09:10:06 2013
Thread-1: Thu Mar 21 09:10:07 2013
Exiting Thread-1
Thread-2: Thu Mar 21 09:10:08 2013
Thread-2: Thu Mar 21 09:10:10 2013
Thread-2: Thu Mar 21 09:10:12 2013
Exiting Thread-2
也可以如下使用:
import time, threading
# 新線程執(zhí)行的代碼:
def loop():
print 'thread %s is running...' % threading.current_thread().name
n = 0
while n < 5:
n = n + 1
print 'thread %s >>> %s' % (threading.current_thread().name, n)
time.sleep(1)
print 'thread %s ended.' % threading.current_thread().name
def create_thread():
# 啟動(dòng)一個(gè)線程就是把一個(gè)函數(shù)傳入并創(chuàng)建Thread實(shí)例伊磺,然后調(diào)用start()開始執(zhí)行
# 由于任何進(jìn)程默認(rèn)就會(huì)啟動(dòng)一個(gè)線程盛正,我們把該線程稱為主線程,主線程又可以啟動(dòng)新的線程
print 'thread %s is running...' % threading.current_thread().name
t = threading.Thread(target=loop, name='LoopThread')
t.start()
t.join()
print 'thread %s ended.' % threading.current_thread().name
if __name__ == '__main__':
create_thread()
# more_threading()
運(yùn)行結(jié)果:
thread MainThread is running...
thread LoopThread is running...
thread LoopThread >>> 1
thread LoopThread >>> 2
thread LoopThread >>> 3
thread LoopThread >>> 4
thread LoopThread >>> 5
thread LoopThread ended.
thread MainThread ended.
鎖
#!/usr/bin/python
import threading
import time
class myThread_Lock (threading.Thread):
def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print "Starting " + self.name
# Get lock to synchronize threads
threadLock.acquire()
print_time_second(self.name, self.counter, 3)
# Free lock to release next thread
threadLock.release()
def print_time_second(threadName, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadName, time.ctime(time.time()))
counter -= 1
def test_lock():
threads = []
# Create new threads
thread1 = myThread_Lock(1, "Thread-1", 1)
thread2 = myThread_Lock(2, "Thread-2", 2)
# Start new Threads
thread1.start()
thread2.start()
# Add threads to thread list
threads.append(thread1)
threads.append(thread2)
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
if __name__ == "__main__":
# test()
test_lock()
運(yùn)行結(jié)果:
Starting Thread-1
Starting Thread-2
Thread-1: Thu Mar 21 09:11:28 2013
Thread-1: Thu Mar 21 09:11:29 2013
Thread-1: Thu Mar 21 09:11:30 2013
Thread-2: Thu Mar 21 09:11:32 2013
Thread-2: Thu Mar 21 09:11:34 2013
Thread-2: Thu Mar 21 09:11:36 2013
Exiting Main Thread
再來(lái)
#!/usr/bin/python
import Queue
import threading
import time
exitFlag = 0
class myThread (threading.Thread):
def __init__(self, threadID, name, q):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.q = q
def run(self):
print "Starting " + self.name
process_data(self.name, self.q)
print "Exiting " + self.name
def process_data(threadName, q):
while not exitFlag:
queueLock.acquire()
if not workQueue.empty():
data = q.get()
queueLock.release()
print "%s processing %s" % (threadName, data)
else:
queueLock.release()
time.sleep(1)
threadList = ["Thread-1", "Thread-2", "Thread-3"]
nameList = ["One", "Two", "Three", "Four", "Five"]
queueLock = threading.Lock()
workQueue = Queue.Queue(10)
threads = []
threadID = 1
# Create new threads
for tName in threadList:
thread = myThread(threadID, tName, workQueue)
thread.start()
threads.append(thread)
threadID += 1
# Fill the queue
queueLock.acquire()
for word in nameList:
workQueue.put(word)
queueLock.release()
# Wait for queue to empty
while not workQueue.empty():
pass
# Notify threads it's time to exit
exitFlag = 1
# Wait for all threads to complete
for t in threads:
t.join()
print "Exiting Main Thread"
運(yùn)行結(jié)果:
Starting Thread-1
Starting Thread-2
Starting Thread-3
Thread-1 processing One
Thread-2 processing Two
Thread-3 processing Three
Thread-1 processing Four
Thread-2 processing Five
Exiting Thread-3
Exiting Thread-1
Exiting Thread-2
Exiting Main Thread
再來(lái):
import time, threading
balance = 0
lock = threading.Lock()
def change_it(n):
# 先存后取奢浑,結(jié)果應(yīng)該為0:
global balance
balance = balance + n
balance = balance - n
def run_thread_uselock(n):
# 當(dāng)多個(gè)線程同時(shí)執(zhí)行l(wèi)ock.acquire()時(shí)蛮艰,只有一個(gè)線程能成功地獲取鎖,然后繼續(xù)執(zhí)行代碼,其他線程就繼續(xù)等待直到獲得鎖為止壤蚜。
for i in range(100000):
# 先要獲取鎖:
lock.acquire()
try:
# 放心地改吧:
change_it(n)
finally:
# 改完了一定要釋放鎖:
lock.release()
def run_thread(n):
for i in range(100000):
change_it(n)
def more_threading():
# 多線程和多進(jìn)程最大的不同在于即寡,多進(jìn)程中,同一個(gè)變量袜刷,各自有一份拷貝存在于每個(gè)進(jìn)程中聪富,互不影響,
# 而多線程中著蟹,所有變量都由所有線程共享墩蔓,所以,任何一個(gè)變量都可以被任何一個(gè)線程修改萧豆,
# 因此奸披,線程之間共享數(shù)據(jù)最大的危險(xiǎn)在于多個(gè)線程同時(shí)改一個(gè)變量,把內(nèi)容給改亂了涮雷。
# t1 = threading.Thread(target=run_thread, args=(5,))
# t2 = threading.Thread(target=run_thread, args=(8,))
t3 = threading.Thread(target=run_thread_uselock, args=(5,))
t4 = threading.Thread(target=run_thread_uselock, args=(8,))
# t1.start()
# t2.start()
# t1.join()
# t2.join()
t3.start()
t4.start()
t3.join()
t4.join()
print balance # result may not be 0,but it should be 0 in normal.
if __name__ == '__main__':
# create_thread()
more_threading()
運(yùn)行結(jié)果:0