您好,登錄后才能下訂單哦!
示例代碼:
#!/usr/bin/python3
import time
from threading import Thread
def countdown(n):
while n > 0:
print('倒數(shù)開始:', n)
n -= 1
time.sleep(1)
def main():
t = Thread(target=countdown, args=(5, )) # target=函數(shù)名,args=() 給target=的函數(shù)傳參數(shù),參數(shù)以元組形式傳,如果只有一個,要加逗號
t.start() # 啟動線程
if __name__ == '__main__':
main()
輸出:
倒數(shù)開始: 5
倒數(shù)開始: 4
倒數(shù)開始: 3
倒數(shù)開始: 2
倒數(shù)開始: 1
示例代碼:
#!/usr/bin/python3
import time
from threading import Thread
def countdown(n, number):
while n > 0:
print(f'第{number}個線程,倒數(shù)開始:', n)
n -= 1
time.sleep(1)
def main():
for i in range(3):
t = Thread(target=countdown, args=(5, i+1))
t.start()
if __name__ == '__main__':
main()
輸出:
第1個線程,倒數(shù)開始: 5
第2個線程,倒數(shù)開始: 5
第3個線程,倒數(shù)開始: 5
第3個線程,倒數(shù)開始: 4
第2個線程,倒數(shù)開始: 4
第1個線程,倒數(shù)開始: 4
第3個線程,倒數(shù)開始: 3
第2個線程,倒數(shù)開始: 3
第1個線程,倒數(shù)開始: 3
第1個線程,倒數(shù)開始: 2
第2個線程,倒數(shù)開始: 2
第3個線程,倒數(shù)開始: 2
第1個線程,倒數(shù)開始: 1
第2個線程,倒數(shù)開始: 1
第3個線程,倒數(shù)開始: 1
示例代碼:
#!/usr/bin/python3
import time
import threading
from threading import Thread
def countdown(n, number):
while n > 0:
print(f'第{number}個線程,倒數(shù)開始:', threading.current_thread().name, n)
n -= 1
time.sleep(1)
def main():
for i in range(3):
t = Thread(target=countdown, args=(5, i+1))
t.start()
if __name__ == '__main__':
main()
輸出:
第1個線程,倒數(shù)開始: Thread-1 5
第2個線程,倒數(shù)開始: Thread-2 5
第3個線程,倒數(shù)開始: Thread-3 5
第1個線程,倒數(shù)開始: Thread-1 4
第2個線程,倒數(shù)開始: Thread-2 4
第3個線程,倒數(shù)開始: Thread-3 4
第1個線程,倒數(shù)開始: Thread-1 3
第2個線程,倒數(shù)開始: Thread-2 3
第3個線程,倒數(shù)開始: Thread-3 3
第3個線程,倒數(shù)開始: Thread-3 2
第2個線程,倒數(shù)開始: Thread-2 2
第1個線程,倒數(shù)開始: Thread-1 2
第3個線程,倒數(shù)開始: Thread-3 1
第2個線程,倒數(shù)開始: Thread-2 1
第1個線程,倒數(shù)開始: Thread-1 1
示例代碼:
#!/usr/bin/python3
# 當前線程結(jié)束后再執(zhí)行下一個
import time
import threading
from threading import Thread
def countdown(n, number):
while n > 0:
print(f'第{number}個線程,倒數(shù)開始:', threading.current_thread().name, n)
n -= 1
time.sleep(1)
def main():
for i in range(3):
t = Thread(target=countdown, args=(3, i+1))
t.start()
t.join() # waite until the thread terminates 前面線程結(jié)束之后再執(zhí)行下一個
if __name__ == '__main__':
main()
輸出:
第1個線程,倒數(shù)開始: Thread-13 3
第1個線程,倒數(shù)開始: Thread-13 2
第1個線程,倒數(shù)開始: Thread-13 1
第2個線程,倒數(shù)開始: Thread-14 3
第2個線程,倒數(shù)開始: Thread-14 2
第2個線程,倒數(shù)開始: Thread-14 1
第3個線程,倒數(shù)開始: Thread-15 3
第3個線程,倒數(shù)開始: Thread-15 2
第3個線程,倒數(shù)開始: Thread-15 1
示例代碼:
#!/usr/bin/python3
import time
import logging
import threading
from threading import Thread
logging.basicConfig(
level=logging.DEBUG,
format='%(threadName)-10s: %(message)s',
) # format 中的 threadName 可以捕獲到線程的名字,所以下邊logging.debug()中不需要傳入線程名
def countdown(n, number):
while n > 0:
# print(f'{threading.current_thread().name}-倒數(shù)開始:', n)
logging.debug(f'倒數(shù)開始:{n}')
n -= 1
time.sleep(1)
def main():
thread_list = []
logging.debug('start.....')
for i in range(3):
t = Thread(target=countdown, args=(3, i+1))
t.start()
thread_list.append(t) # 把線程放到列表中
for i in thread_list: # 終止列表中的線程
i.join()
logging.debug('end.....')
if __name__ == '__main__':
main()
輸出:
MainThread: start.....
Thread-1 : 倒數(shù)開始:3
Thread-2 : 倒數(shù)開始:3
Thread-3 : 倒數(shù)開始:3
Thread-1 : 倒數(shù)開始:2
Thread-3 : 倒數(shù)開始:2
Thread-2 : 倒數(shù)開始:2
Thread-2 : 倒數(shù)開始:1
Thread-3 : 倒數(shù)開始:1
Thread-1 : 倒數(shù)開始:1
MainThread: end.....
示例代碼:
#!/usr/bin/python3
# 繼承 Thread類,定義一個新類,初始化對象
import time
import logging
import threading
from threading import Thread
logging.basicConfig(
level=logging.DEBUG,
format='%(threadName)-10s: %(message)s',
) # format 中的 threadName 可以捕獲到線程的名字,所以下邊logging.debug()中不需要傳入線程名
def countdown(n):
while n > 0:
# print(f'{threading.current_thread().name}-倒數(shù)開始:', n)
logging.debug(f'倒數(shù)開始:{n}')
n -= 1
time.sleep(1)
class MyThread(Thread):
def __init__(self, name, count):
Thread.__init__(self)
self.name = name
self.count = count
def run(self):
countdown(self.count)
def main():
thread_list = []
logging.debug('start.....')
for i in range(3):
t = MyThread(f'thread-{i+1}', 3)
t.start()
thread_list.append(t) # 把線程放到列表中
for i in thread_list: # 終止列表中的線程
i.join()
logging.debug('end.....')
if __name__ == '__main__':
main()
輸出:
MainThread: start.....
thread-1 : 倒數(shù)開始:3
thread-2 : 倒數(shù)開始:3
thread-3 : 倒數(shù)開始:3
thread-3 : 倒數(shù)開始:2
thread-1 : 倒數(shù)開始:2
thread-2 : 倒數(shù)開始:2
thread-3 : 倒數(shù)開始:1
thread-2 : 倒數(shù)開始:1
thread-1 : 倒數(shù)開始:1
MainThread: end.....
示例代碼:
#!/usr/bin/python3
# 給線程加鎖
import time
import logging
import threading
from threading import Thread
logging.basicConfig(
level=logging.DEBUG,
format='%(threadName)-10s: %(message)s',
) # format 中的 threadName 可以捕獲到線程的名字,所以下邊logging.debug()中不需要傳入線程名
def countdown(n):
while n > 0:
logging.debug(f'倒數(shù)開始:{n}')
n -= 1
time.sleep(1)
class MyThread(Thread):
def __init__(self, name, count):
Thread.__init__(self)
self.name = name
self.count = count
def run(self):
try:
lock.acquire() # 獲取鎖
logging.debug('lock....')
countdown(self.count)
finally:
lock.release()
logging.debug('open again')
lock = threading.Lock() # 新建一個鎖
def main():
thread_list = []
logging.debug('start.....')
for i in range(3):
t = MyThread(f'thread-{i+1}', 3)
t.start()
thread_list.append(t) # 把線程放到列表中
for i in thread_list: # 終止列表中的線程
i.join()
logging.debug('end.....')
if __name__ == '__main__':
main()
輸出:
MainThread: start.....
thread-1 : lock....
thread-1 : 倒數(shù)開始:3
thread-1 : 倒數(shù)開始:2
thread-1 : 倒數(shù)開始:1
thread-1 : open again
thread-2 : lock....
thread-2 : 倒數(shù)開始:3
thread-2 : 倒數(shù)開始:2
thread-2 : 倒數(shù)開始:1
thread-2 : open again
thread-3 : lock....
thread-3 : 倒數(shù)開始:3
thread-3 : 倒數(shù)開始:2
thread-3 : 倒數(shù)開始:1
thread-3 : open again
MainThread: end.....
示例代碼:
#!/usr/bin/python3
# 防止多個線程同時操作同一個變量
# 鎖,多線程修改全局變量
# 執(zhí)行時,后邊加線程個數(shù);例如python xxx.py 5
import time
import logging
import threading
import random
import sys
from threading import Thread
logging.basicConfig(
level=logging.DEBUG,
format='%(threadName)-10s: %(message)s',
) # format 中的 threadName 可以捕獲到線程的名字,所以下邊logging.debug()中不需要傳入線程名
def countdown(n):
while n > 0:
# print(f'{threading.current_thread().name}-倒數(shù)開始:', n)
logging.debug(f'倒數(shù)開始:{n}')
n -= 1
time.sleep(1)
class MyThread(Thread):
def __init__(self, name, count):
Thread.__init__(self)
self.name = name
self.count = count
def run(self):
try:
lock.acquire() # 獲取鎖
logging.debug('lock....')
countdown(self.count)
finally:
lock.release()
logging.debug('open again')
lock = threading.Lock() # 新建一個鎖
TOTAL = 0
def add_plus():
global TOTAL
with lock: # 鎖的新用法,用完之后可以自動關閉
logging.debug(f'before add:{TOTAL}')
wait = random.randint(1, 3)
time.sleep(wait)
print(f'執(zhí)行了{wait}s之后。。。')
TOTAL += 1
logging.debug(f'after add:{TOTAL}')
def main():
thread_list = []
logging.debug('start.....')
for i in range(int(sys.argv[1])):
t = Thread(target=add_plus)
t.start()
thread_list.append(t) # 把線程放到列表中
for i in thread_list: # 終止列表中的線程
i.join()
logging.debug('end.....')
if __name__ == '__main__':
main()
輸出:
MainThread: start.....
Thread-1 : before add:0
執(zhí)行了3s之后。。。
Thread-1 : after add:1
Thread-2 : before add:1
執(zhí)行了2s之后。。。
Thread-2 : after add:2
Thread-3 : before add:2
執(zhí)行了1s之后。。。
Thread-3 : after add:3
Thread-4 : before add:3
執(zhí)行了2s之后。。。
Thread-4 : after add:4
Thread-5 : before add:4
執(zhí)行了3s之后。。。
Thread-5 : after add:5
MainThread: end.....
常規(guī)情況下出現(xiàn)鎖嵌套,程序會卡住
這里用RLock
示例代碼:
#!/usr/bin/python3
# 出現(xiàn)鎖嵌套時,要用threading.RLock建立鎖,否則程序會出問題
import time
import logging
import threading
import random
import sys
from threading import Thread
logging.basicConfig(
level=logging.DEBUG,
format='%(threadName)-10s: %(message)s',
) # format 中的 threadName 可以捕獲到線程的名字,所以下邊logging.debug()中不需要傳入線程名
def countdown(n):
while n > 0:
logging.debug(f'倒數(shù)開始:{n}')
n -= 1
time.sleep(1)
class MyThread(Thread):
def __init__(self, name, count):
Thread.__init__(self)
self.name = name
self.count = count
def run(self):
try:
lock.acquire() # 獲取鎖
logging.debug('lock....')
countdown(self.count)
finally:
lock.release()
logging.debug('open again')
# lock = threading.Lock() # 新建一個鎖
lock = threading.RLock() # 可以用于鎖嵌套
TOTAL = 0
def add_plus_3():
global TOTAL
with lock:
TOTAL += 3
def add_plus():
global TOTAL
with lock: # 鎖的新用法,用完之后可以自動關閉
logging.debug(f'before add:{TOTAL}')
wait = random.randint(1, 3)
time.sleep(wait)
print(f'執(zhí)行了{wait}s之后。。。')
TOTAL += 1
logging.debug(f'after add:{TOTAL}')
add_plus_3()
def main():
thread_list = []
logging.debug('start.....')
for i in range(int(sys.argv[1])):
t = Thread(target=add_plus)
t.start()
thread_list.append(t) # 把線程放到列表中
for i in thread_list: # 終止列表中的線程
i.join()
logging.debug('end.....')
if __name__ == '__main__':
main()
輸出:
MainThread: start.....
Thread-1 : before add:0
執(zhí)行了3s之后。。。
Thread-1 : after add:1
Thread-2 : before add:4
執(zhí)行了3s之后。。。
Thread-2 : after add:5
Thread-3 : before add:8
執(zhí)行了3s之后。。。
Thread-3 : after add:9
Thread-4 : before add:12
執(zhí)行了2s之后。。。
Thread-4 : after add:13
Thread-5 : before add:16
執(zhí)行了3s之后。。。
Thread-5 : after add:17
MainThread: end.....
隊列queue,先時先出的讀寫規(guī)則
示例代碼:
#!/usr/bin/python3
from queue import Queue
q = Queue()
q.put(1)
q.put(2)
q.put(3)
q.get(block=False) # 加上block=False防止取完所有之后卡住
q.get(block=False)
q.get(block=False)
輸出:
1
2
3
示例代碼:
# 取得線程中的結(jié)果
from queue import Queue # 用隊列來保存線程的結(jié)果,先進先出
from threading import Thread
q_result = Queue() # 新建一個隊列對象
str_list = ['1', '3', '6', '8']
def str_to_int(arg, queue):
result = int(arg) # 將列表中的字符串轉(zhuǎn)換成數(shù)字
queue.put({arg: result})
def main():
thread_list = []
for s in str_list:
t = Thread(target=str_to_int, args=(s, q_result))
t.start()
thread_list.append(t)
for i in thread_list:
i.join()
return [q_result.get() for _ in range(len(str_list))] # 列表生成式,等同于上邊的for循環(huán)
if __name__ == '__main__':
print(main()) # 打印main()中的return 內(nèi)容
輸出:
[{'1': 1}, {'3': 3}, {'6': 6}, {'8': 8}]
測試多線程與非多線程性能
示例代碼:
#!/usr/bin/python3
# 多線程與非多線程時間對比
# 測試多線程是否適合I/O密集型,用時間加減來檢測多線程與非多線程
import time
from queue import Queue # 用隊列來保存線程的結(jié)果,先進先出
from threading import Thread
q_result = Queue() # 新建一個隊列對象
str_list = ['1', '3', '6', '8']
def str_to_int(arg, queue):
result = int(arg)
queue.put({arg: result})
def with_thread():
thread_list = []
start_time = time.time()
for s in str_list:
t = Thread(target=str_to_int, args=(s, q_result))
t.start()
thread_list.append(t)
for i in thread_list:
i.join()
print('with thread:', (time.time() - start_time) * 1000) # 顯示毫秒
return [q_result.get() for _ in range(len(str_list))]
def no_thread():
start_time = time.time()
q = Queue()
for s in str_list:
str_to_int(s, q)
print('no thread:', (time.time() - start_time) * 1000) # 顯示毫秒
return [q.get() for _ in range(len(str_list))]
def main():
no_thread()
with_thread()
if __name__ == '__main__':
main()
輸出:
no thread: 0.0
with thread: 1.996755599975586
對比I/O操作時,多線程與非多線程的性能
示例代碼:
# 用I/O操作來檢測多線程與非多線程處理任務所花的時間
# 測試多線程是否適合I/O密集型,用時間加減來檢測多線程與非多線程
#!/usr/bin/python3
import time
from queue import Queue # 用隊列來保存線程的結(jié)果,先進先出
from threading import Thread
import requests
q_result = Queue() # 新建一個隊列對象
urls = [
"http://www.baidu.com",
"http://www.qq.com",
"http://www.360.com",
"http://www.baidu.com",
"http://www.qq.com",
"http://www.360.com",
"http://www.baidu.com",
"http://www.qq.com",
"http://www.360.com",
]
def get_page(url, queue):
result = requests.get(url).content # 獲取頁面內(nèi)容
queue.put(result[:10]) # 保存前10個字符
with open('utl.txt', 'ab') as f:
f.write(result[:100])
def with_thread():
thread_list = []
start_time = time.time()
for s in urls:
t = Thread(target=get_page, args=(s, q_result))
t.start()
thread_list.append(t)
for i in thread_list:
i.join()
print('with thread:', (time.time() - start_time) * 1000) # 顯示毫秒
return [q_result.get() for _ in range(len(urls))]
def no_thread():
start_time = time.time()
q = Queue()
for s in urls:
get_page(s, q)
print('no thread:', (time.time() - start_time) * 1000) # 顯示毫秒
return [q.get() for _ in range(len(urls))]
def main():
print(no_thread()) # 打印return的內(nèi)容
print(with_thread())
if __name__ == '__main__':
main()
輸出:
no thread: 1418.3428287506104
[b'<!DOCTYPE ', b'<!DOCTYPE ', b'<!Doctype ', b'<!DOCTYPE ', b'<!DOCTYPE ', b'<!Doctype ', b'<!DOCTYPE ', b'<!DOCTYPE ', b'<!Doctype ']
with thread: 346.4798927307129
[b'<!DOCTYPE ', b'<!DOCTYPE ', b'<!DOCTYPE ', b'<!DOCTYPE ', b'<!DOCTYPE ', b'<!DOCTYPE ', b'<!Doctype ', b'<!Doctype ', b'<!Doctype ']PS D:\python\project>
示例代碼:
#!/usr/bin/python3
from concurrent.futures import ThreadPoolExecutor, as_completed
import logging
import requests
urls = [
"http://www.baidu.com",
"http://www.qq.com",
"http://www.360.com",
"http://www.baidu.com",
"http://www.qq.com",
"http://www.360.com",
"http://www.baidu.com",
"http://www.qq.com",
"http://www.360.com",
]
logging.basicConfig(
level=logging.DEBUG,
format='%(threadName)-10s: %(message)s',
)
def download(url):
r = requests.get(url)
return url, r.status_code
def main():
with ThreadPoolExecutor(5, thread_name_prefix='yhyang') as executor:
# 創(chuàng)建一個5個線程的池
# 方法1:
# futures = [executor.submit(download, url) for url in urls]
# submit 返回一個future對象,futures值為一個包含多個future對象的列表
# for future in as_completed(futures):
# # as_completed(futures) 得到一個可迭代的對象
# try:
# print(future.result())
# except Exception as e:
# print(e)
# 方法2:map() 是對方法1中submit()的一個封裝,簡化了使用方法
futures_result = executor.map(download, urls, timeout=30)
for future in futures_result:
try:
print(future)
except Exception as e:
print(e)
if __name__ == '__main__':
main()
輸出:
yhyang_0 : Starting new HTTP connection (1): www.baidu.com
yhyang_1 : Starting new HTTP connection (1): www.qq.com
yhyang_2 : Starting new HTTP connection (1): www.360.com
yhyang_3 : Starting new HTTP connection (1): www.baidu.com
yhyang_4 : Starting new HTTP connection (1): www.qq.comyhyang_0 : http://www.baidu.com:80 "GET / HTTP/1.1" 200 None
('http://www.baidu.com', 200)
yhyang_0 : Starting new HTTP connection (1): www.360.com
yhyang_1 : http://www.qq.com:80 "GET / HTTP/1.1" 200 None
yhyang_3 : http://www.baidu.com:80 "GET / HTTP/1.1" 200 Noneyhyang_3 : Starting new HTTP connection (1): www.baidu.com
yhyang_4 : http://www.qq.com:80 "GET / HTTP/1.1" 200 None
('http://www.qq.com', 200)
yhyang_1 : Starting new HTTP connection (1): www.qq.com
yhyang_3 : http://www.baidu.com:80 "GET / HTTP/1.1" 200 None
yhyang_2 : http://www.360.com:80 "GET / HTTP/1.1" 301 178
yhyang_3 : Starting new HTTP connection (1): www.360.com
yhyang_2 : Starting new HTTPS connection (1): www.#
yhyang_0 : http://www.360.com:80 "GET / HTTP/1.1" 301 178
yhyang_0 : Starting new HTTPS connection (1): www.#
yhyang_1 : http://www.qq.com:80 "GET / HTTP/1.1" 200 None
yhyang_3 : http://www.360.com:80 "GET / HTTP/1.1" 301 178
yhyang_3 : Starting new HTTPS connection (1): www.#
yhyang_0 : https://www.#:443 "GET / HTTP/1.1" 200 None
yhyang_3 : https://www.#:443 "GET / HTTP/1.1" 200 None
yhyang_2 : https://www.#:443 "GET / HTTP/1.1" 200 None
('http://www.360.com', 200)
('http://www.baidu.com', 200)
('http://www.qq.com', 200)
('http://www.360.com', 200)
('http://www.baidu.com', 200)
('http://www.qq.com', 200)
('http://www.360.com', 200)
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。