import _thread
import time
# 為執行緒定義乙個函式
defprint_time
(threadname, delay)
: count =
0while count <3:
time.sleep(delay)
count +=
1print
(threadname, time.ctime())
# 建立兩個執行緒
try:
_thread.start_new_thread(print_time,
("thread-1",1
))# 休眠1秒
_thread.start_new_thread(print_time,
("thread-2",2
))# 休眠2秒
except
:print
("error: unable to start thread"
)while1:
pass
和_thread幾乎一樣,但是使用threading能夠有效控制線程,將在網路爬蟲中發揮更好的效果
import threading
import time
class
thread
(threading.thread)
:def
__init__
(self, name, delay)
: threading.thread.__init__(self)
self.name = name
self.delay = delay
defrun(self)
:print
("starting"
+ self.name)
print_time(self.name, self.delay)
print
("exiting"
+ self.name)
defprint_time
(thread_name, delay)
: count =
0while count <3:
time.sleep(delay)
print
(thread_name, time.ctime())
count +=
1threads =
# 建立新執行緒
thread1 = thread(
"thread-1",1
)thread2 = thread(
"thread-2",2
)# 開啟新執行緒
thread1.start(
)thread2.start(
)# 新增執行緒到執行緒列表
# 等待所有執行緒完成
for t in threads:
t.join(
)print
("exiting main thread"
)
3.python多執行緒同步輸出1-100的數
import threading, time
defworker()
:global count
while
true
: lock.acquire(
)# 加鎖
count +=
1print
(threading.current_thread(
), count)
lock.release(
)# 操作完成後釋放鎖
if count >=99:
break
time.sleep(
0.1)
if __name__ ==
'__main__'
: lock = threading.lock(
) count =
0 threads =
for i in
range(2
):# 控制線程的數量
t = threading.thread(target=worker, args=()
)for i in threads:
i.start(
)for i in threads:
i.join(
)# 將執行緒加入到主線程中
參考:
1.python多執行緒詳解(超詳細)
2.python多執行緒同步輸出1-100的數
python 多執行緒(十三 1)
玩遊戲 for i in range 3 print 玩遊戲 time.sleep 5 def network 上網 for i in range 3 print 上網.time.sleep 5 呼叫 單任務的表現 當25行 play函式呼叫沒有執行完畢之前。26行不會被執行,也就是會阻塞。play...
Python多執行緒(1)新增執行緒
基本指令 新增執行緒 import threading defthread job print this is an added thread,number is s n threading.current thread defmain added threading threading.threa...
python多執行緒 python多執行緒
通常來說,多程序適用於計算密集型任務,多執行緒適用於io密集型任務,如網路爬蟲。關於多執行緒和多程序的區別,請參考這個 下面將使用python標準庫的multiprocessing包來嘗試多執行緒的操作,在python中呼叫多執行緒要使用multiprocessing.dummy,如果是多程序則去掉...