# encoding=utf-8
# 傳統的方式
# 執行 3 次
# def coding():
# for x in range(3):
# print('正在寫**%s' %x)
# time.sleep(1)
## def drawing():
# for x in range(3):
# print('正在畫圖%s' %x)
# time.sleep(1)
## def main():
# coding()
# drawing()
## if __name__ == '__main__':
# main()
import time
import threading
# 採用多執行緒的方式:
# 執行 3 次
defcoding()
:for x in
range(3
):print
('正在寫**%s'
%threading.current_thread())
time.sleep(1)
defdrawing()
:for x in
range(3
):print
('正在畫圖%s'
%threading.current_thread())
time.sleep(1)
defmain()
:# threading.thread 建立乙個子執行緒
# target 執行緒被建立完成後執行哪個**
# 注:傳遞函式時,只需要傳遞函式的名字
# 而coding(): 代表返回值
t1 = threading.thread(target=coding)
t2 = threading.thread(target=drawing)
t1.start(
) t2.start(
)print
(threading.
enumerate()
)if __name__ ==
'__main__'
: main(
)
2.thread類:
# encoding=utf-8
import threading
import time
class
codingthread
(threading.thread)
:def
run(self)
:for x in
range(3
):print
('正在寫**%s'
%threading.current_thread())
time.sleep(1)
class
drawingthread
(threading.thread)
:def
run(self)
:for x in
range(3
):print
('正在畫圖%s'
%threading.current_thread())
time.sleep(1)
defmain()
: t1 = codingthread(
) t2= drawingthread(
) t1.start(
) t2.start(
)if __name__ ==
'__main__'
: main(
)
3.共享全域性變數的問題
# encoding=utf-8
import threading
value =
0# 建立鎖
glock = threading.lock(
)def
add_value()
:# 全域性變數需用 global 宣告
global value
# 上鎖
glock.acquire(
)# 執行次數
for x in
range
(10000000):
value +=
1# 釋放
glock.release(
)print
('value, %d'
%value)
defmain()
:for x in
range(2
):t =threading.thread(target=add_value())
t.start(
)if __name__ ==
'__main__'
: main(
)
python 多執行緒演練3
1.queue執行緒安全佇列 encoding utf 8 from queue import queue import time import threading 佇列有四個 q queue 4 for x in range 4 q.put x for x in range 4 print q.g...
Python小爬蟲, 多執行緒
下面是初學了多執行緒,下手寫的乙個小爬蟲,個人看著不那麼優雅,無奈水平不夠 望您發現有誤或者有改進的地方,能指正 import urllib.request as ur import re from threading import thread as tt from queue import qu...
python 多執行緒小練習
需求 有100個資料,啟動5個執行緒,每個執行緒分20個資料,怎麼把這20個資料分別傳給每個執行緒。1.利用多執行緒實現 import threading nums list range 100 defp nums for num in numss print num threads for i i...