Day18 線程

1 單線程

每個進程默認都有一個線程,這個線程叫主線程; 其他的線程都叫子線程

# 單線程下載兩個電影
# 在一個線程中下載兩個電影:時間是兩個電影下載的總和
def download(film_name):
    print('開始下載: %s' % film_name, datetime.now())
    time.sleep(5)
    print('%s下載完成' % film_name, datetime.now())
download('復(fù)聯(lián)5')
download('007')

2 多線程

2.1 線程模塊

current_thread函數(shù)   -   獲取當(dāng)前線程

print(threading.current_thread())

2.2 Thread類

  • Thread類的對象就是線程,所以需要子線程就創(chuàng)建這個類的對象
  • 方法: Thread(target,args,kwargs)
    • target - 函數(shù), 需要在當(dāng)前創(chuàng)建的子線程中去調(diào)用的函數(shù)
    • args/kwargs - 調(diào)用target中的函數(shù)需要的實參列表
# a.創(chuàng)建線程對象
t1 = threading.Thread(target=download, args=('復(fù)聯(lián)5',))
# t1 = threading.Thread(target=download, kwargs={'film_name': '復(fù)聯(lián)5'})
t2 = threading.Thread(target=download, args=('007',))

# b.開始執(zhí)行子線程中的任務(wù): 線程對象.start()
"""
通過start方法,在子線程中去調(diào)用target對應(yīng)的函數(shù)
"""
t1.start()
t2.start()

2.3 創(chuàng)建自己的線程類

  • 方法: 聲明一個類繼承Thread 實現(xiàn)run方法,這個方法中的任務(wù)就是需要在子線程中執(zhí)行的任務(wù)
  • 注意: 一個進程中如果有多個線程,程序會在所有的線程都結(jié)束的時候才結(jié)束;發(fā)生異常崩潰其實奔潰的是線程
class DownloadThread(Thread):
    def __init__(self, film_name):
        super().__init__()
        self.film_name = film_name

    def run(self):
        # print(current_thread())
        # print('在子線程中執(zhí)行的代碼')
        print('開始下載: %s' % self.film_name, datetime.now())
        print([1, 2][3])
        time.sleep(6)
        print('結(jié)束下載: %s' % self.film_name, datetime.now())


# 用子類直接創(chuàng)建線程對象
t1 = DownloadThread('復(fù)聯(lián)4')
t2 = DownloadThread('長江7號')
# 通過start去執(zhí)行子線程中的任務(wù)
t1.start()
t2.start()
# t1.run()    # 不能直接調(diào)用run方法,因為這樣調(diào)用不會在子線程中執(zhí)行任務(wù)

2.4 多線程套接字

2.4.1 多線程服務(wù)器

from socket import *
from threading import *


class ChatThread(Thread):
    def __init__(self, connect: socket, address):
        super().__init__()
        self.connect = connect
        self.address = address

    def run(self):
        while True:
            self.connect.send('你好,我是余婷!'.encode())

            message = self.connect.recv(1024)
            print('%s:%s' % (self.address[0], message.decode(encoding='utf-8')))

        connect.close()


server = socket()
server.bind(('10.7.185.82', 8888))
server.listen(512)
while True:
    # 接收請求
    connect, address = server.accept()

    # 給每個請求創(chuàng)建一個線程,來聊天
    t = ChatThread(connect, address)
    t.start()

2.4.2 多線程客戶端套接字

from socket import socket

client = socket()
client.connect(('10.7.185.82', 8888))
while True:
    message = client.recv(1024)
    print(message.decode(encoding='utf-8'))

    send_message = input('>>>')
    client.send(send_message.encode())

2.5 join

如果希望某個任務(wù)是在某個線程結(jié)束后才執(zhí)行,那就將這個任務(wù)的帶放在對應(yīng)線程對象調(diào)用join方法的后面

from threading import Thread
from datetime import datetime
import time
from random import randint

class DownloadThread(Thread):
    def __init__(self, name, time):
        super().__init__()
        self.name = name
        self.time = time

    def run(self):
        print('開始下載:%s' % self.name)
        time.sleep(self.time)
        print('下載結(jié)束:%s' % self.name)

t1 = DownloadThread('沉默的羔羊', 5)
t2 = DownloadThread('恐怖游輪', 7)

t2.start()
t1.start()

t1.join()
t2.join()
print('下載完成') # 多有都下載完成才打印

print('=============================')
t1 = DownloadThread('沉默的羔羊', 4)
t2 = DownloadThread('恐怖游輪', 5)
t2.start()
t2.join()
t1.start()# 下載完恐怖游輪才下載沉默的羔羊

2.6 多線程資源共享

  • 問題: 當(dāng)多個線程同時對一個數(shù)據(jù)進行讀寫操作,可能會出現(xiàn)一個線程剛把數(shù)據(jù)讀出來還沒來得及寫進去,另外一個線程進行讀操作的數(shù)據(jù)安全問題。
  • 解決 - 加鎖
    • 保證每個數(shù)據(jù)對應(yīng)一個鎖對象
    • 操作數(shù)據(jù)前加鎖,數(shù)據(jù)操作完成后釋放鎖
import time
from threading import Thread, Lock

class Account:
    def __init__(self, name, tel, balance=50):
        self.name = name
        self.tel = tel
        self.balance = balance
        # 關(guān)聯(lián)一個鎖對象
        self.lock = Lock()

    def save_money(self, money):
        print('開始存錢')
        # 加鎖
        self.lock.acquire()
        value = self.balance
        time.sleep(4)
        self.balance = value+money
        print('存錢成功: %.2f' % self.balance)
        # 釋放鎖
        self.lock.release()

    def draw_money(self, money):
        print('開始取錢')
        # 加鎖
        self.lock.acquire()
        value = self.balance
        time.sleep(5)
        if value < money:
            print('取錢失??!余額不足')
            return
        self.balance = value - money
        print('取錢成功:%.2f' % self.balance)
        # 釋放鎖
        self.lock.release()


acount = Account('張三', '15300022703', 10000)

# 一個線程去存錢
t1 = Thread(target=acount.save_money, args=(1000,))
# 一個線程去取錢
t2 = Thread(target=acount.draw_money, args=(500,))
# t1.start()
# t2.start()
  • 單條數(shù)據(jù)加鎖
share_data = 1000
lock = Lock()


def add_data(value):
    lock.acquire()
    global share_data
    old_data = share_data
    time.sleep(4)
    share_data = old_data + value
    lock.release()

t1 = Thread(target=add_data, args=(200,))
t2 = Thread(target=add_data, args=(300,))
t1.start()
t2.start()

t1.join()
t2.join()

print(share_data)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 線程 操作系統(tǒng)線程理論 線程概念的引入背景 進程 之前我們已經(jīng)了解了操作系統(tǒng)中進程的概念,程序并不能單獨運行,只有...
    go以恒閱讀 1,793評論 0 6
  • 一、Python簡介和環(huán)境搭建以及pip的安裝 4課時實驗課主要內(nèi)容 【Python簡介】: Python 是一個...
    _小老虎_閱讀 6,319評論 0 10
  • Swift1> Swift和OC的區(qū)別1.1> Swift沒有地址/指針的概念1.2> 泛型1.3> 類型嚴謹 對...
    cosWriter閱讀 11,629評論 1 32
  • 多線程 1、進程 指系統(tǒng)中正在運行的一個引用程序叫進程 每個進程之間是獨立的,每個進程均運行在其專用且受保護的內(nèi)存...
    ququququ閱讀 252評論 0 0
  • ??一個任務(wù)通常就是一個程序,每個運行中的程序就是一個進程。當(dāng)一個程序運行時,內(nèi)部可能包含了多個順序執(zhí)行流,每個順...
    OmaiMoon閱讀 1,801評論 0 12

友情鏈接更多精彩內(nèi)容