python_note
  • Introduction
  • My Python
    • Anaconda
    • argparse
    • datetime
    • json
    • logging
    • numpy
    • open
    • openCC
    • pandas & csv
    • Socket & SocketServer
    • re
    • yaml
    • smtp
    • 物件操作
    • unittest
    • 線程
    • prettytable
    • IO
    • pycurl
    • sys
    • pickle
    • auto-python-to-exe
    • cython
    • nuitka
  • Crawler
    • Urllib & Requests
      • User-agent
      • Percent-Encoding
      • mail code
    • Selenium
    • TCP & UDP
    • 控制字符(control character)
  • Web Development
    • Flask
      • RESTful api
      • Template
      • blueprint
    • Django
      • 環境佈署(windows)
    • 檢查Port
    • Apache
    • 使用者行為
    • jQuery
    • 壓力測試
    • DataTable
    • Bootstrap
    • CSS
    • JavaScript
    • Chart.js
  • Deep Learning
    • Keras 設定
    • RNN
    • LSTM
  • Test
    • T-Test
  • 資料結構
    • Hash
    • 時間複雜度
  • NLP
    • N-gram
    • CKIP
    • 中文轉數字
    • CRF
    • Mutual Information
    • 模糊比對
  • Linebot
    • Heroku
    • 圖文選單
    • channel
  • Linux
    • 常用指令
    • shell script
    • sshfs
    • ssh
    • nodejs & npm
    • debug
  • GCP
    • app engine
    • ssh(gcp)
    • gsutil
    • brabrabra
    • Load Balancer
    • k8s
  • Database
    • mysql
    • elasticsearch
      • Query
      • Backup and Restore
      • elasticdump
      • es2csv
      • ELK
    • mongodb
      • install
      • authentication
      • pymongo
    • sql server
  • go
    • Swarm
  • Docker
    • Kitematic
    • Dockerfile
    • Swarm
  • Git
  • 其他
    • USB軟體保護
    • Windows效能監視器
  • Blockchain
Powered by GitBook
On this page
  • join() vs setDaemon()
  • GIL(Global Interpreter Lock)
  • CPU密集型 VS I/O密集型
  • concurrent.futures

Was this helpful?

  1. My Python

線程

PreviousunittestNextprettytable

Last updated 5 years ago

Was this helpful?

python的多線程並不是真正平行運算,即使一個程式開啟了多線程,在同一時間中真正在運行的線程只有一個,其他線程則是等待獲得GIL後才能進行,整體來說就是交替執行

1個程式只擁有一個GIL,如果想真正達到平行運算則需使用多進程(multiprocessing)

join --> 主線程等待子線程完成後才繼續執行(可設置timeout),start()後再加入join屬性

setDaemon --> 主線程不等子線程,需在線程start()之前設定

start與join的順序():

#先全部start 再全部join,
cores=[core1,core2]
for c in cores:
    c.start()
for c in cores:
    c.join()

GIL(Global Interpreter Lock)

一個進程中都有一個GIL,線程必須取得GIL後才能運行,達到特定條件(ticks)後該線程才會釋出GIL,換下一個線程運行

CPU密集型 VS I/O密集型

CPU密集型 --> 各種for、if邏輯判斷,較花費CPU資源,容易觸發GIL交換,多線程不適合處理此問題,可能因為GIL轉換導致程式效率更差

I/O密集型 --> 讀寫文件、爬蟲,可以在線程等待回應時啟動另一線程執行新任務,避免浪費等待時間,多線程在此問題中效果較明顯

concurrent.futures

額 外參考資料

比較1
比較2(範例)
線程概念
線程概念[2]
查看線程與核心數
線程簡易範例-python
線程爬蟲範例-python
join() vs setDaemon()
url
https://www.jianshu.com/p/e3a2df19c41a
http://www.cnblogs.com/kaituorensheng/p/4445418.html#_label4
https://blog.aweimeow.tw/Cheatsheet-for-python-subprocess/