2016-03-03 46 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)]