2016-03-03 86 views
0

我的問題是我想循環與一些線程數組,每個線程然後將值添加到全局數組。但由於某些原因陣列來按計劃進行,我注意到,你需要使用join()的線程函數,但我就有點糊塗瞭如何在這裏加入python線程,總計

totalPoints = [] 

def workThread(i): 
    global totalPoints 
    totalPoints += i 


threads = [] 
for i in range(NUMBER_OF_THREADS): 
    t = threading.Thread(target=workThread, args=(i,)) 
    t.start() 
    threads.append(t) 

實現它的任何幫助,將不勝感激。謝謝!

回答

1

你只寫了第二循環的加入線程

totalPoints = [] 

def workThread(i): 
    global totalPoints 
    totalPoints += i 

threads = [] 
for i in range(NUMBER_OF_THREADS): 
    t = threading.Thread(target=workThread, args=(i,)) 
    t.start() 
    threads.append(t) 
for t in threads: 
    t.join() 

您的代碼將在totalPoints += i失敗,因爲totalPoints是一個列表。你不會在你的線程中處理異常,所以你可能會默默地失敗,不知道發生了什麼。另外,您需要小心如何訪問諸如totalPoints之類的共享資源以確保線程安全。

0

是否有幫助:?

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

import threading 
import time 
import random 

NUMBER_OF_THREADS=20 

totalPoints = [] 

def workThread(i): 
    global totalPoints 
    time.sleep(random.randint(0, 5)) 
    totalPoints.append((i, random.randint(0, 255))) 

threads = [] 
for i in range(NUMBER_OF_THREADS): 
    t = threading.Thread(target=workThread, args=(i,)) 
    t.start() 
    threads.append(t) 

for t in threads: 
    t.join() 
print totalPoints 

它始終打印是這樣的:

[(1, 126), (10, 169), (11, 154), (0, 214), (9, 243), (12, 13), (15, 152), (6, 24), (17, 238), (13, 28), (19, 78), (16, 130), (2, 110), (3, 186), (8, 55), (14, 70), (5, 35), (4, 39), (7, 11), (18, 14)] 

或本

[(2, 132), (3, 53), (4, 15), (6, 84), (8, 223), (12, 39), (14, 220), (0, 128), (9, 244), (13, 80), (19, 99), (7, 184), (11, 232), (17, 191), (18, 207), (1, 177), (5, 186), (16, 63), (15, 179), (10, 143)]