iT邦幫忙

1

PYTHONE DAY13 多線呈中代碼疑問

  • 分享至 

  • xImage

網路教材:
下面的例子演示了100个线程向同一个银行账户转账(转入1元钱)的场景,在这个例子中,银行账户就是一个临界资源,在没有保护的情况下我们很有可能会得到错误的结果。

from time import sleep
from threading import Thread


class Account(object):

    def __init__(self):
        self._balance = 0

    def deposit(self, money):
        # 计算存款后的余额
        new_balance = self._balance + money
        # 模拟受理存款业务需要0.01秒的时间
        sleep(0.01)
        # 修改账户余额
        self._balance = new_balance

    @property
    def balance(self):
        return self._balance


class AddMoneyThread(Thread):

    def __init__(self, account, money):
        super().__init__()
        self._account = account
        self._money = money

    def run(self):
        self.account.deposit(self.money) ###
        這段為什麼會被運行呢


def main():
    account = Account()
    threads = []
    # 创建100个存款的线程向同一个账户中存钱
    for _ in range(100):
        t = AddMoneyThread(account, 1)
        threads.append(t)
        t.start()
    # 等所有存款的线程都执行完毕
    for t in threads:
        t.join()
    print('账户余额为: ¥%d元' % account.balance)


if __name__ == '__main__':
    main()

其中###這段程式碼為何會被運行,在main()中並沒有呼叫run 程式是如何運作完成將創建帳戶的1元存入,有大大能稍微解說下嗎(感恩

圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

1 個回答

1
haward79
iT邦研究生 2 級 ‧ 2021-08-16 19:02:25
最佳解答

請參考 python 中關於 Thread 的定義

run()

representing the thread’s activity.

You may override this method in a subclass. The standard run() method invokes the callable object passed to the object’s constructor as the target argument, if any, with positional and keyword arguments taken from the args and kwargs arguments, respectively.

簡單來說:
run() 是 Thread 類別當中本來就有的方法
執行 Thread 時
本來就會執行 run() 中的程式

因為定義類別 AddMoneyThread 時
傳入了 Thread 作為引數
所以 AddMoneyThread 繼承了 Thread 當中所有的屬性及方法
再者,AddMoneyThread 中有定義 run()
所以 AddMoneyThread 中的 run() 會 override 原本 Thread 中的 run()

所以雖然 AddMoneyThread 中的 run()
沒有被「直接」呼叫
但是也會在 thread 執行時「間接」被呼叫並執行

我要發表回答

立即登入回答