Python多線程使用和註意事項

来源:https://www.cnblogs.com/xuyiqing/archive/2019/01/20/10293833.html
-Advertisement-
Play Games

多線程 基本實現: 第一種,函數方式 # -*- coding:utf-8 -*- import thread import time def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) co ...


多線程   基本實現: 第一種,函數方式 # -*- coding:utf-8 -*- import thread import time     def print_time(threadName, delay):     count = 0     while count < 5:         time.sleep(delay)         count += 1         print '%s : %s' % (threadName, time.ctime(time.time()))     try:     thread.start_new_thread(print_time, ("Thread-1", 2,))     thread.start_new_thread(print_time, ("Thread-2", 4,)) except:     print "Error!Unable to start thread."   while 1:     pass   第二種,繼承父類 # -*- coding:utf-8 -*- import threading import time     class MyThread(threading.Thread):     def __init__(self, thread_id, name, counter):         threading.Thread.__init__(self)         self.thread_id = thread_id         self.name = name         self.counter = counter       def run(self):         print "Starting:" + self.name         print_time(self.name, self.counter, 5)         print "Exiting:" + self.name     def print_time(thread_name, delay, counter):     while counter:         time.sleep(delay)         print '%s : %s' % (thread_name, time.ctime(time.time()))         counter -= 1     thread1 = MyThread(1, "Thread-1", 1) thread2 = MyThread(2, "Thread-2", 2)   thread1.start() thread2.start()   線程同步的問題解決:鎖 這裡第一個線程執行的時候,第二個線程是等待狀態的 # -*- coding:utf-8 -*- import threading import time   threadLock = threading.Lock() threads = []     class MyThread(threading.Thread):     def __init__(self, thread_id, name, counter):         threading.Thread.__init__(self)         self.thread_id = thread_id         self.name = name         self.counter = counter       def run(self):         print "Starting:" + self.name         threadLock.acquire()         print_time(self.name, self.counter, 5)         print "Exiting:" + self.name         threadLock.release()     def print_time(thread_name, delay, counter):     while counter:         time.sleep(delay)         print '%s : %s' % (thread_name, time.ctime(time.time()))         counter -= 1     thread1 = MyThread(1, "Thread-1", 1) thread2 = MyThread(2, "Thread2", 2)   thread1.start() thread2.start()   threads.append(thread1) threads.append(thread2)   for thread in threads:     thread.join()   線程優先順序隊列: 雖然開啟了多個線程,不過列印順序一定是:one按順序到five # -*- coding:utf-8 -*- import threading import time import Queue   exit_flag = 0 queue_lock = threading.Lock() work_queue = Queue.Queue(10) thread_list = ["Thread-1", "Thread-2", "Thread-3"] name_list = ["one", "two", "three", "four", "five"] threads = [] thread_id = 1     class MyThread(threading.Thread):     def __init__(self, thread__id, name, queue):         threading.Thread.__init__(self)         self.thread__id = thread__id         self.name = name         self.queue = queue       def run(self):         print "Starting:" + self.name         process_data(self.name, self.queue)         print "Exiting:" + self.name     def process_data(thread_name, queue):     while not exit_flag:         queue_lock.acquire()         if not work_queue.empty():             data = queue.get()             queue_lock.release()             print "%s processing %s" % (thread_name, data)         else:             queue_lock.release()         time.sleep(2)     for t in thread_list:     thread = MyThread(thread_id, t, work_queue)     thread.start()     threads.append(thread)     thread_id += 1   queue_lock.acquire() for word in name_list:     work_queue.put(word) queue_lock.release()   while not work_queue.empty():     pass   exit_flag = 1   for t in threads:     t.join()   這裡的join函數重點解釋下: join的原理就是依次檢驗線程池中的線程是否結束,沒有結束就阻塞主線程直到其他線程結束,如果結束則跳轉執行下一個線程的join函數   接下來看看多線程實際的案例: 多線程訪問網站 # -*- coding:utf-8 -*- import urllib2 import time from threading import Thread     class GetUrlThread(Thread):     def __init__(self, url):         Thread.__init__(self)         self.url = url       def run(self):         response = urllib2.urlopen(self.url)         print self.url, response.getcode()     def get_responses():     urls = [         'https://www.baidu.com',         'https://www.taobao.com',         'https://www.cnblogs.com',         'https://github.com',         'https://www.jd.com'     ]     start = time.time()     threads = []     for url in urls:         thread = GetUrlThread(url)         threads.append(thread)         thread.start()       for thread in threads:         thread.join()       print "Time: % s" % (time.time() - start)     get_responses()   如果多個線程訪問同一個變數,容易出問題,比如下麵: 有可能最後的實際值並不是50 # -*- coding:utf-8 -*- from threading import Thread   some_var = 0     class IncrementThread(Thread):     def run(self):         global some_var         read_value = some_var         print "線程%s中的some_var是%d" % (self.name, read_value)         some_var = read_value + 1         print "線程%s中的some_var增加後變成%d" % (self.name, some_var)     def use_increment_thread():     threads = []     for i in range(50):         thread = IncrementThread()         threads.append(thread)         thread.start()       for thread in threads:         thread.join()       print "在50次運算後some_var應該變成50"     print "在50次運算後some_var實際值為:%d" % (some_var,)     use_increment_thread()   解決辦法,加入一個鎖: 這種情況,最後的實際值一定是50 # -*- coding:utf-8 -*- from threading import Thread, Lock   lock = Lock() some_var = 0     class IncrementThread(Thread):     def run(self):         global some_var         lock.acquire()         read_value = some_var         print "線程%s中的some_var是%d" % (self.name, read_value)         some_var = read_value + 1         print "線程%s中的some_var增加後變成%d" % (self.name, some_var)         lock.release()     def use_increment_thread():     threads = []     for i in range(50):         thread = IncrementThread()         threads.append(thread)         thread.start()       for thread in threads:         thread.join()       print "在50次運算後some_var應該變成50"     print "在50次運算後some_var實際值為:%d" % (some_var,)     use_increment_thread()   另一個鎖的案例: 不加鎖容易出事 # -*- coding:utf-8 -*- from threading import Thread import time     class CreateListThread(Thread):     def __init__(self):         self.entries = []         Thread.__init__(self)       def run(self):         self.entries = []         for i in range(10):             time.sleep(1)             self.entries.append(i)         print self.entries     def use_create_list_thread():     for i in range(3):         t = CreateListThread()         t.start()     use_create_list_thread() 結果: [[[000, , , 111, , , 222, , , 333, , , 444, , , 555, , , 666, , , 777, , , 888, , , 999]]]   給他加上鎖: # -*- coding:utf-8 -*- from threading import Thread, Lock import time   lock = Lock()     class CreateListThread(Thread):     def __init__(self):         self.entries = []         Thread.__init__(self)       def run(self):         self.entries = []         for i in range(10):             time.sleep(1)             self.entries.append(i)         lock.acquire()         print self.entries         lock.release()     def use_create_list_thread():     for i in range(3):         t = CreateListThread()         t.start()     use_create_list_thread() 結果: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 寫這篇文章之前,關於ubuntu14.04(Trusty)預設安裝的NodeJS版本是0.10.25百思不解(什麼鬼,哪一年的NodeJS) 寫這篇文章之時,NodeJS的LTS版本號都已經10.15.0,當然Ubuntu在2018年也都發行ubuntu18.04(我還沒打算用) 系統我可以用4... ...
  • Cropper.js是一款很好用的圖片裁剪工具,可以對圖片的尺寸、寬高比進行裁剪,滿足諸如裁剪頭像上傳、商品圖片編輯之類的需求。 github: https://github.com/fengyuanchen/cropperjs 網站: https://fengyuanchen.github.io/ ...
  • 最近在陸續做機房升級相關工作,配合DBA對產線資料庫鏈接方式做個調整,將原來直接鏈接讀庫的地址切換到統一的讀負載均衡的代理 haproxy 上,方便機櫃和伺服器的搬遷。 切換之後線上時不時的會發生 discard connection 錯誤,導致程式報 500 錯誤,但不是每次都必現的。 開發框... ...
  • 對 .NET 自帶的 BinaryReader、BinaryWriter 進行擴展. NuGet 上安裝 Syroot.IO.BinaryData 即可使用. ...
  • 一.資料庫概述 1.什麼是資料庫?先來看看百度怎麼說的. 資料庫,簡而言之可視為電子化的文件櫃——存儲電子文件的處所,用戶可以對文件中的數據運行新增、截取、更新、刪除等操作。 所謂“資料庫”系以一定方式儲存在一起、能予多個用戶共用、具有儘可能小的冗餘度、與應用程式彼此獨立的數據集合。 資料庫,簡而言 ...
  • 一、Akka簡介 Akka時spark的底層通信框架,Hadoop的底層通信框架時rpc。 併發的程式編寫很難,但是Akka解決了spark的這個問題。 Akka構建在JVM平臺上,是一種高併發、分散式、並且容錯的應用工具包; Akka使用Scala語言編寫,同時它提供了Scala和Java的開發接 ...
  • 為什麼突然在此提到這個梳理問題呢? 因為在自己實踐綜合練習學過的知識時,突然覺得有些知識點的運用總是不成功,於是翻過課本進行回顧,總是覺得是對的,可是當再進一步思考“既然是對的,為什麼在程式中總是不成功呢?”,後來發現,自己理所當然的理解(忽略了細節知識),導致程式通不過,現在結合同一個類中的不同方 ...
  • # 介面類:python 原生不支持# 抽象類:python 原生支持的 介面類 首先我們來看一個支付介面的簡單例子 介面類的多繼承 這是三種動物tiger 走路 游泳swan 走路 游泳 飛oldying 走路 飛 為了避免代碼重覆,我們寫以下三個類下麵就是實現了 介面類的規範 不需要有功能實現的 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...