如何从python线程访问数据

乔恩

我有一个使用Python 3.4.2的非常简单的线程示例。在此示例中,我创建了五个线程,这些线程仅返回字符串“ Result”并将其附加到名为线程的数组中。在另一个for循环中,迭代五次将线程连接到项x。我正在尝试打印结果x,它应该产生一个看起来像['Resut','Result','Result','Result','Result']的列表,但print命令只产生线程的标题和它是封闭的事实。我显然误会了如何在python中使用线程。如果有人可以提供如何充分完成此测试用例的示例,我将不胜感激。

 import threading

 def Thread_Test():
     return ("Result")

 number  = 5
 threads = []
 for i in range(number):
     Result = threading.Thread(target=Thread_Test)
     threads.append(Result)
     Result.start()

 for x in threads:
     x.join()
 print (x)
巴尔加夫

请找到以下有关队列和线程的简单示例,

import threading
import Queue
import timeit

q = Queue.Queue()
number = 5

t1 = timeit.default_timer()
# Step1: For example, we are running multiple functions normally
result = []
def fun(x):
    result.append(x)
    return x

for i in range(number):
    fun(i)
print result ," # normal result"
print (timeit.default_timer() - t1)

t2 = timeit.default_timer()   

#Step2:  by using threads and queue

def fun_thrd(x,q):
    q.put(x)
    return
for i in range(number):
    t1 = threading.Thread(target = fun_thrd, args=(i,q))
    t1.start()
    t1.join()

thrd_result = []

while True:
    if not q.empty():
     thrd_result.append(q.get())
    else:
       break

print thrd_result , "# result with threads involved"
print (timeit.default_timer() - t2)

t3 = timeit.default_timer() 

#step :3 if you want thread to be run without depending on the previous thread

threads = []

def fun_thrd_independent(x,q):
    q.put(x)
    return

def thread_indep(number):
    for i in range(number):
        t = threading.Thread(target = fun_thrd_independent, args=(i,q))
        t.start()
        threads.append(t)

thread_indep(5)

for j in threads:
    j.join()

thread_indep_result = []

while True:
    if not q.empty():
        thread_indep_result.append(q.get())
    else:
       break

print thread_indep_result # result when threads are independent on each other   
print (timeit.default_timer() - t3)

输出:

[0, 1, 2, 3, 4]  # normal result
3.50475311279e-05
[0, 1, 2, 3, 4] # result with threads involved
0.000977039337158
[0, 1, 2, 3, 4]  result when threads are independent on each other
0.000933170318604

根据数据规模的不同会有很大的不同

希望这会有所帮助,谢谢

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章