加入python线程,总计

时间:2016-03-03 19:23:47

标签: python multithreading

我的问题是我正在尝试使用多个线程循环一个数组,然后每个线程将值添加到全局数组中。但由于某种原因,数组按计划推出,我注意到你需要使用join()线程函数,但是对于如何在这里实现它有点困惑

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)

任何帮助将不胜感激。谢谢!

2 个答案:

答案 0 :(得分: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)以保证线程安全。

答案 1 :(得分:1)

这有用吗:?

#!/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)]