1、呼叫thread模組中的start_new_thread()函式來產生新執行緒
thread.start_new_thread ( function, args[, kwargs] )
function - 執行緒函式。
args - 傳遞給執行緒函式的引數,他必須是個tuple型別。
kwargs - 可選引數。
2、使用threading模組建立執行緒,直接從threading.thread繼承,然後重寫__init__方法和run方法
別忘了用start函式啟動,並且注意生命週期,必要時用join函式等待執行緒結束。
3、執行緒同步,即加鎖
使用thread物件的lock和rlock可以實現簡單的執行緒同步,這兩個物件都有acquire方法和release方法,對於那些需要每次只允許乙個執行緒操作的資料,可以將其操作放到acquire和release方法之間。
4、優先順序佇列
# queue.queue,先進先出佇列
# queue.lifoqueue,後進先出佇列
# queue.priorityqueue,優先順序佇列
# queue.deque,雙向對隊
如:workqueue = queue.queue(10) 容納10個執行緒的先進先出佇列
workqueue = queue.queue(10) 容納無數個執行緒的先進先出佇列
python佇列、執行緒、程序、協程:
python多執行緒:
執行緒同步例子:
#!/usr/bin/python
# -*- coding: utf-8 -*-
import threading
import time
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
# 獲得鎖,成功獲得鎖定後返回true
# 可選的timeout引數不填時將一直阻塞直到獲得鎖定
# 否則超時後將返回false
threadlock.acquire()
print_time(self.name, self.counter, 3)
# 釋放鎖
threadlock.release()
def print_time(threadname, delay, counter):
while counter:
time.sleep(delay)
print "%s: %s" % (threadname, time.ctime(time.time()))
counter -= 1
threadlock = threading.lock()
threads =
# 建立新執行緒
thread1 = mythread(1, "thread-1", 1)
thread2 = mythread(2, "thread-2", 2)
# 開啟新執行緒
thread1.start()
thread2.start()
# 新增執行緒到執行緒列表
# 等待所有執行緒完成
for t in threads:
t.join()
print "exiting main thread"
python之多執行緒
學習了一下多執行緒 用到爬蟲裡面簡直爽歪歪呀 定義就很簡單,為了實現高併發,能夠同時在乙個指令碼下執行多個程式,節約時間 新增執行緒用到的 import threading as td def sum num1,num2 sum num1 num2 print sss sum def divided...
python之多執行緒
我們在商超買東西時,當只有乙個收銀台時,會導致排很長的隊。如果有多個收銀台同時工作的話,會大大提高效率。這是生活中的多執行緒,即多個執行緒同時工作。我們接下來用 案例講解多執行緒與單執行緒的區別。單執行緒即在程式執行過程中,按照一定的先後順序執行。多執行緒即多個事件同時發生。單執行緒 import ...
Python之多執行緒
mythread類是我自己實現的乙個類,繼承自threading模組中的thread類,在子類中重寫run方法,當程序呼叫start方法時候,子類的run方法會被呼叫 工作需要,現學現賣,獻醜了 created on may 28,2013 author berlin import threadin...