Python從新手到大師——12:進(jìn)程和線程

代碼一

author = 'damao'

from random import randint
from time import time,sleep
from multiprocessing import Process
from os import getpid


def download_file(file_name):
    print("開始下載{a}".format(a=file_name))
    download_use_time = randint(1,10)
    sleep(download_use_time)
    print("{a}下載完成骂蓖,共耗時秒".format(a=file_name,b=download_use_time))

"""未使用多進(jìn)程代碼"""
def test():
    start_time = time()
    download_file("Python核心編程.pdf")
    download_file("av.mp4")
    end_time = time()
    totle_time = end_time - start_time
    print("共耗時{a}秒".format(a=round(totle_time,3)))

"""使用多進(jìn)程代碼"""
def test_use_process():
    start_time = time()
    p1 = Process(target=download_file,args=("C語言編程.pdf",))
    p1.start()
    p2 = Process(target=download_file,args=("tykohot.avi",))
    p2.start()
    p1.join()
    p2.join()
    end_time = time()
    totle_time = end_time - start_time
    print("共耗時{a}秒".format(a=round(totle_time, 3)))

    

if __name__ == '__main__':
    # test()
    test_use_process()

代碼二

author = 'damao'

"""控制總‘進(jìn)程’數(shù)"""

from multiprocessing import Process,Queue
from time import sleep

def func(words,q):
    num = q.get()
    while num:
        print("{a}:捞镰".format(a=num,b=words))
        sleep(0.001)
        num = q.get()

def test():
    q = Queue(10)  # 指定進(jìn)程數(shù)
    for num in range(1,11):
        q.put(num)
    Process(target=func,args=("good",q)).start()
    Process(target=func,args=("great",q)).start()

if __name__ == '__main__':
    test()  

代碼三

author = 'damao'

"""使用threading模塊實(shí)現(xiàn)多線程"""

from threading import Thread
from random import randint
from time import time,sleep

def download_file(file_name):
    print("開始下載{a}".format(a=file_name))
    download_use_time = randint(1,10)
    sleep(download_use_time)
    print("{a}下載完成旅急,共耗時独泞秒".format(a=file_name,b=download_use_time))

"""使用多進(jìn)程代碼"""
def test_use_thread():
    start_time = time()
    p1 = Thread(target=download_file,args=("C語言編程.pdf",))
    p1.start()
    p2 = Thread(target=download_file,args=("tykohot.avi",))
    p2.start()
    p1.join()
    p2.join()
    end_time = time()
    totle_time = end_time - start_time
    print("共耗時{a}秒".format(a=round(totle_time, 3)))

"""###########################################################"""


"""自定義線程類"""


class MyThread(Thread):
    def __init__(self,file_name):
        super().__init__()
        self.file_name = file_name

    def run(self):
        print("開始下載{a}".format(a=self.file_name))
        download_use_time = randint(1, 10)
        sleep(download_use_time)
        print("{a}下載完成资溃,共耗時羔飞秒".format(a=self.file_name, b=download_use_time))

def main():
    start_time = time()
    p1 = MyThread("NNN.pdf")
    p1.start()
    p2 = MyThread("AAA.mp4")
    p2.start()
    p1.join()
    p2.join()
    end_time = time()
    use_time = end_time - start_time
    print("共耗時{a}秒".format(a=round(use_time, 3)))


if __name__ == '__main__':
    # test_use_thread()
    main()


代碼四

author = 'damao'

from random import randint
from threading import Thread
from time import time, sleep


class MyThread(Thread):

    def __init__(self,file_name):
        super().__init__()
        self._file_name = file_name

    def run(self):
        print("開始下載{a}".format(a=self._file_name))
        download_use_time = randint(1, 10)
        sleep(download_use_time)
        print("{a}下載完成拼岳,共耗時偿荷秒".format(a=self._file_name, b=download_use_time))

def main():
    start_time = time()
    p1 = MyThread("NNN.pdf")
    p1.start()
    p2 = MyThread("AAA.mp4")
    p2.start()
    p1.join()
    p2.join()
    end_time = time()
    use_time = end_time - start_time
    print("共耗時{a}秒".format(a=round(use_time, 3)))


if __name__ == '__main__':
    # test_use_thread()
    main()

代碼五

author = 'damao'

from time import sleep
from threading import Thread,Lock

class SaveMoney(object):

    def __init__(self):
        self._balance = 0
        self._lock = Lock()

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

    def save_meony(self,moeny):
        # 先獲取鎖才能進(jìn)行后續(xù)的操作
        self._lock.acquire()
        try:
            new_balance = self._balance + moeny
            sleep(0.01)
            self._balance = new_balance
        finally:
            # 在finally中執(zhí)行釋放鎖的操作保證正常異常鎖都能釋放
            self._lock.release()


class AddMoneyThread(Thread):
    """存錢多程序"""

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

    def run(self):
        self._account.save_meony(self._money)


def main():
    my_money = SaveMoney()
    save_money_threads = []
    for _ in range(100):
        t = AddMoneyThread(my_money,1)
        save_money_threads.append(t)
        t.start()
    for i in save_money_threads:
        i.join()
    print("賬戶余額為:{a}元".format(a=my_money.balance))


if __name__ == '__main__':
    main()

代碼六

import time
import tkinter
import tkinter.messagebox
from threading import Thread


def main():

    class DownloadTaskHandler(Thread):

        def run(self):
            time.sleep(10)
            tkinter.messagebox.showinfo('提示', '下載完成!')
            # 啟用下載按鈕
            button1.config(state=tkinter.NORMAL)

    def download():
        # 禁用下載按鈕
        button1.config(state=tkinter.DISABLED)
        # 通過daemon參數(shù)將線程設(shè)置為守護(hù)線程(主程序退出就不再保留執(zhí)行)
        # 在線程中處理耗時間的下載任務(wù)
        DownloadTaskHandler(daemon=True).start()

    def show_about():
        tkinter.messagebox.showinfo('關(guān)于', '作者: 駱昊(v1.0)')

    top = tkinter.Tk()
    top.title('單線程')
    top.geometry('200x150')
    top.wm_attributes('-topmost', 1)

    panel = tkinter.Frame(top)
    button1 = tkinter.Button(panel, text='下載', command=download)
    button1.pack(side='left')
    button2 = tkinter.Button(panel, text='關(guān)于', command=show_about)
    button2.pack(side='right')
    panel.pack(side='bottom')

    tkinter.mainloop()


if __name__ == '__main__':
    main()

代碼七

author = 'damao'

"""完成1~100000000求和"""

import time

# 方法一  共耗時4.673534870147705
def to_sum():
    stat_time = time.time()
    sum = 0
    for i in range(1,100000001):
        sum += i
    print(sum)
    end_time = time.time()
    totle_time = end_time - stat_time
    print("共耗時{a}".format(a=totle_time))

# 方法二  共耗時11.168128728866577
def test_sum():
    stat_time = time.time()
    num_list = [x for x in range(1,100000001)]
    a = sum(num_list)
    print(a)
    end_time = time.time()
    totle_time = end_time - stat_time
    print("共耗時{a}".format(a=totle_time))


if __name__ == '__main__':
    # to_sum()
    test_sum()
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末窘游,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子跳纳,更是在濱河造成了極大的恐慌忍饰,老刑警劉巖,帶你破解...
    沈念sama閱讀 216,496評論 6 501
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件寺庄,死亡現(xiàn)場離奇詭異艾蓝,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)斗塘,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,407評論 3 392
  • 文/潘曉璐 我一進(jìn)店門赢织,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人馍盟,你說我怎么就攤上這事于置。” “怎么了贞岭?”我有些...
    開封第一講書人閱讀 162,632評論 0 353
  • 文/不壞的土叔 我叫張陵八毯,是天一觀的道長。 經(jīng)常有香客問我瞄桨,道長话速,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,180評論 1 292
  • 正文 為了忘掉前任芯侥,我火速辦了婚禮泊交,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己活合,他們只是感情好雏婶,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,198評論 6 388
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著白指,像睡著了一般留晚。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上告嘲,一...
    開封第一講書人閱讀 51,165評論 1 299
  • 那天错维,我揣著相機(jī)與錄音,去河邊找鬼橄唬。 笑死赋焕,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的仰楚。 我是一名探鬼主播隆判,決...
    沈念sama閱讀 40,052評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼僧界!你這毒婦竟也來了侨嘀?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 38,910評論 0 274
  • 序言:老撾萬榮一對情侶失蹤捂襟,失蹤者是張志新(化名)和其女友劉穎咬腕,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體葬荷,經(jīng)...
    沈念sama閱讀 45,324評論 1 310
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡涨共,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,542評論 2 332
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了宠漩。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片举反。...
    茶點(diǎn)故事閱讀 39,711評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖哄孤,靈堂內(nèi)的尸體忽然破棺而出照筑,到底是詐尸還是另有隱情吹截,我是刑警寧澤瘦陈,帶...
    沈念sama閱讀 35,424評論 5 343
  • 正文 年R本政府宣布,位于F島的核電站波俄,受9級特大地震影響晨逝,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜懦铺,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,017評論 3 326
  • 文/蒙蒙 一捉貌、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦趁窃、人聲如沸牧挣。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,668評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽瀑构。三九已至,卻和暖如春刨摩,著一層夾襖步出監(jiān)牢的瞬間寺晌,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,823評論 1 269
  • 我被黑心中介騙來泰國打工澡刹, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留呻征,地道東北人。 一個月前我還...
    沈念sama閱讀 47,722評論 2 368
  • 正文 我出身青樓罢浇,卻偏偏與公主長得像陆赋,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子嚷闭,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,611評論 2 353