1. 程式人生 > >Python 線程與進程

Python 線程與進程

主線程 watch 操作 方法 完成 music list 繼續 threading

線程是操作系統能夠進行運算調度的最小單位。它被包含在進程之中,是進程中的實際運作單位。一條線程指的是進程中一個單一順序的控制流,一個進程中可以並發多個線程,每條線程並行執行不同的任務。

使用 threading 模塊

方法一:

import threading
import time

def foo(n):
    print(‘foo %s‘%n)
    time.sleep(1)
    print(‘end foo‘)


def bar(n):
    print(‘bar %s‘%n)
    time.sleep(2)
    print(‘end bar‘)

t1 = threading.Thread(target=foo, args=(1,))
t2 = threading.Thread(target=bar, args=(2,))
t1.start()
t2.start()

print(‘........in the main..........‘)

運行結果:
foo 1
bar 2
........in the main..........
end foo
end bar

方法二:

import time, threading

class MyThread(threading.Thread):

    def __init__(self, num):
        threading.Thread.__init__(self)
        self.num = num

    def run(self):             #定義線程要運行的函數
        print("running on number:%s" % self.num)
        time.sleep(3)

if __name__ == ‘__main__‘:
    t1 = MyThread(1)
    t2 = MyThread(2)
    t1.start()
    t2.start()

運行結果:
running on number:1
running on number:2

join 方法使得主線程等待子線程完成才繼續

import threading
import time

begin = time.time()

def foo(n):
    print(‘foo %s‘%n)
    time.sleep(1)
    print(‘end foo‘)


def bar(n):
    print(‘bar %s‘%n)
    time.sleep(2)
    print(‘end bar‘)

t1 = threading.Thread(target=foo, args=(1,))
t2 = threading.Thread(target=bar, args=(2,))
t1.start()
t2.start()


t1.join()
t2.join()
print(‘........in the main..........‘)

運行結果:
foo 1
bar 2
end foo
end bar
........in the main..........

在計算密集型任務中串行與多線程進行對比

import threading, time

begin = time.time()

def add(n):
    sum = 0
    for i in range(n):
        sum += i
    print(sum)

add(100000000)
add(200000000)
end = time.time()
print(end-begin)

運行結果:
4999999950000000
19999999900000000
17.66856598854065


import threading, time

begin = time.time()

def add(n):
    sum = 0
    for i in range(n):
        sum += i
    print(sum)

t1 = threading.Thread(target=add, args=(100000000,))
t1.start()
t2 = threading.Thread(target=add, args=(200000000,))
t2.start()
t1.join()
t2.join()
end = time.time()
print(end-begin)

運行結果:
4999999950000000
19999999900000000
21.088160276412964

# 結果為串行運行比多線程運行更快

Cpython 中有 GIL (Global Interpreter Lock,全局解釋器鎖),所以在同一時刻,只能有一個線程進入調度。如果任務是IO密集型的,可以使用多線程;如果任務是計算密集型的,最優方法是改成 C。


setDaemon()

調用該方法只要是主線程完成,不管子線程是否完成都要和主線程一起退出。

threading.currentThread()

返回當前的線程變量。

threading.active_count()

返回正在運行的線程數量。

import threading, time
from time import ctime,sleep

def music(func):
    print(threading.current_thread())
    for i in range(2):
        print("Begin listening to %s. %s" %(func, ctime()))
        sleep(2)
        print("end listening %s" %ctime())


def movie(func):
    print(threading.current_thread())
    for i in range(2):
        print("Begin watching at the %s %s" %{func, ctime()})
        sleep(4)
        print("end watching %s" %ctime())


threads = []
t1 = threading.Thread(target=music, args=(‘klvchen‘,))
threads.append(t1)
t2 = threading.Thread(target=movie, args=(‘lili‘,))
threads.append(t2)


if __name__ == ‘__main__‘:
    for t in threads:
        t.setDaemon(True)
        t.start()

    print(threading.current_thread())
    print(threading.active_count())
    print("all over %s" %ctime())

運行結果:
<Thread(Thread-1, started daemon 5856)>
Begin listening to klvchen. Wed Jul 11 23:43:51 2018
<Thread(Thread-2, started daemon 9124)>
<_MainThread(MainThread, started 9444)>
3
all over Wed Jul 11 23:43:51 2018

Python 線程與進程