并發(fā)編程—?jiǎng)?chuàng)建多線程的三種方式

#!/usr/local/bin/python3
"""
多線程程序如果沒有競(jìng)爭(zhēng)資源的場(chǎng)景那么通常會(huì)比較簡(jiǎn)單
臨界資源 - 被多個(gè)線程競(jìng)爭(zhēng)的資源
當(dāng)多個(gè)線程競(jìng)爭(zhēng)臨界資源的時(shí)候如果缺乏必要的保護(hù)措施就會(huì)導(dǎo)致數(shù)據(jù)錯(cuò)亂
"""
import time
import threading

from concurrent.futures import ThreadPoolExecutor


class Account(object):
    """銀行賬戶"""

    def __init__(self):
        self.balance = 0.0
        self.lock = threading.Lock()

    def deposit(self, money):
        # 通過(guò)鎖保護(hù)臨界資源
        # 可以寫try-finally也可以使用上下文語(yǔ)法
        # self.lock.acquire()
        # try:
        #     pass
        # finally:
        #     self.lock.release()
        with self.lock:
            new_balance = self.balance + money
            time.sleep(0.001)
            self.balance = new_balance


def add_money(account, money):
    account.deposit(money)


# 自定義線程類
class AddMoneyThread(threading.Thread):

    def __init__(self, account, money):
        self.account = account
        self.money = money
        # 自定義線程的初始化方法中必須調(diào)用父類的初始化方法
        super().__init__()

    # run方法是線程啟動(dòng)之后要執(zhí)行的回調(diào)方法(鉤子函數(shù))
    # 所以啟動(dòng)線程不能夠直接調(diào)用run方法而是通過(guò)start方法啟動(dòng)線程
    # 什么時(shí)候需要使用回調(diào)式編程?
    # 你知道要做什么但不知道什么時(shí)候會(huì)做這件事情
    def run(self):
        # 線程啟動(dòng)之后要執(zhí)行的操作
        pass

def main():
    account = Account()
    # 創(chuàng)建線程池
    pool = ThreadPoolExecutor(max_workers=10)
    futures = []
    for _ in range(100):
        # 創(chuàng)建線程的第1種方式
        # threading.Thread(
        #     target=add_money, args=(account, 1)
        # ).start()
        # 創(chuàng)建線程的第2種方式
        # AddMoneyThread(account, 1).start()
        # 創(chuàng)建線程的第3種方式
        # 調(diào)用線程池中的線程來(lái)執(zhí)行特定的任務(wù)
        future = pool.submit(add_money, account, 1)
        futures.append(future)
    # 關(guān)閉線程池
    pool.shutdown()
    for future in futures:
        future.result()
    print(account.balance)


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

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

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