Skip to content

Instantly share code, notes, and snippets.

@chairco
Last active June 12, 2018 04:54
Show Gist options
  • Save chairco/1cb06358d1d5723c9306795529e8ed2b to your computer and use it in GitHub Desktop.
Save chairco/1cb06358d1d5723c9306795529e8ed2b to your computer and use it in GitHub Desktop.
Concurrent Parallel introduction, Python 的並行與平行兩三事。

Concurrent(並行)

Thread(線程)

Thread 主要是用來有效利用 CPU 資源的方法。但 Python 使用全局解釋鎖(GIL)的原因,程式碼並不能同時在多核上並行的執行,因此 Python 實際上並無法真的做並行的。

Python 在 Thread 提供兩組接口,一組是thread模塊,提供基礎的,低等級(Low Level)接口,使用Function作為線程的運行體。還有一組是threading模塊,提供更容易使用的基於對象的接口(類似於Java),可以繼承Thread對象來實現線程,還提供了其它一些線程相關的對象,例如Timer,Lock。 原文網址

使用 thread 模塊的例子 原文網址

import thread 

def worker: 
    """thread worker function""" 
    print 'Worker' thread.start_new_thread(worker)

使用 threading 模塊的例子 原文網址

import threading

def worker:
    """thread worker function""" 
    print 'Worker' 
    t = threading.Thread(target=worker) 
    t.start

Reference

使用Python進行並發編程

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment