2017-03-09 74 views
2

我有一個非常簡單的使用Python 3.4.2的線程示例。在這個例子中,我創建了一個只返回字符串「Result」的五個線程,並將其附加到標題爲線程的數組。在另一個for循環中迭代五次,這些線程被連接到術語x。我試圖打印結果x,它應該產生一個看起來像['Resut','Result','Result','Result','Result']的列表,但是print命令只會產生線程的標題以及它已關閉的事實。我顯然誤解如何在python中使用線程。如果有人能提供一個如何充分完成這個測試案例的例子,我將非常感激。如何從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) 
+0

'threading.Thread(target = Thread_Test)'不返回任何結果的線程實例。所以你得到一個線程引用的數組,這些線程引用被打印爲線程名稱。 – Andrey

+1

您需要使用Queue來收集數據,請在此處查找這個概念 https://www.troyfawkes.com/learn-python-multithreading-queues-basics/ – Bhargav

+0

謝謝Andrey,您能否提供一個示例Que用於這樣的示例代碼。 – Jon

回答

1

請找到隊列和線程下面簡單的例子,

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 

這將極大根據數據的規模不同

希望這有助於,謝謝

+0

感謝您的明確示例。有一個問題,應該是t1.join()在for循環之外。不應該循環開始每個線程的執行,然後將結果加入另一個for循環,否則它必須等待一個線程完成才能啓動下一個線程。 – Jon

+0

@Jon它可以是任何方式,取決於你想要什麼..有時你可能想要線程後運行線程。 – Bhargav

+0

謝謝你的補充例子。我的示例問題僅僅是一個高度並行化的數值方法的簡化,我嘗試使用線程來加速計算時間。你的實現看起來實際上需要的時間比正常的結果要長,當我將它應用於我的問題時,它根本沒有加速它,事實上它增加了幾秒鐘的計算。我是否在解決方案中誤讀了某些內容? – Jon

4

創建線程和嘗試從線程獲取值之間有區別。一般而言,您絕不應該嘗試在線程中使用return以向其調用者提供值。這不是線程的工作方式。當你創建一個線程對象時,你必須找出一種不同的方式來獲得線程中計算出的任何值到程序的其他部分。以下是一個簡單的例子,展示瞭如何使用列表返回值。

#! /usr/bin/env python3 
import threading 


def main(): 
    # Define a few variables including storage for threads and values. 
    threads_to_create = 5 
    threads = [] 
    results = [] 
    # Create, start, and store all of the thread objects. 
    for number in range(threads_to_create): 
     thread = threading.Thread(target=lambda: results.append(number)) 
     thread.start() 
     threads.append(thread) 
    # Ensure all threads are done and show the results. 
    for thread in threads: 
     thread.join() 
    print(results) 


if __name__ == '__main__': 
    main() 

如果你絕對堅持,你必須能夠從一個線程的目標返回值的能力,可以使用子類來獲得所需的行爲來覆蓋threading.Thread一些方法。以下顯示了更高級的用法,並演示瞭如果有人希望從新類的run方法繼承並覆蓋該方法,多個方法需要進行更改。此代碼是爲了完整性而提供的,可能不應使用。

#! /usr/bin/env python3 
import sys as _sys 
import threading 


def main(): 
    # Define a few variables including storage for threads. 
    threads_to_create = 5 
    threads = [] 
    # Create, start, and store all of the thread objects. 
    for number in range(threads_to_create): 
     thread = ThreadWithReturn(target=lambda: number) 
     thread.start() 
     threads.append(thread) 
    # Ensure all threads are done and show the results. 
    print([thread.returned for thread in threads]) 


class ThreadWithReturn(threading.Thread): 

    def __init__(self, group=None, target=None, name=None, 
       args=(), kwargs=None, *, daemon=None): 
     super().__init__(group, target, name, args, kwargs, daemon=daemon) 
     self.__value = None 

    def run(self): 
     try: 
      if self._target: 
       return self._target(*self._args, **self._kwargs) 
     finally: 
      del self._target, self._args, self._kwargs 

    def _bootstrap_inner(self): 
     try: 
      self._set_ident() 
      self._set_tstate_lock() 
      self._started.set() 
      with threading._active_limbo_lock: 
       threading._active[self._ident] = self 
       del threading._limbo[self] 

      if threading._trace_hook: 
       _sys.settrace(threading._trace_hook) 
      if threading._profile_hook: 
       threading. _sys.setprofile(threading._profile_hook) 

      try: 
       self.__value = True, self.run() 
      except SystemExit: 
       pass 
      except: 
       exc_type, exc_value, exc_tb = self._exc_info() 
       self.__value = False, exc_value 
       if _sys and _sys.stderr is not None: 
        print("Exception in thread %s:\n%s" % 
          (self.name, threading._format_exc()), file=_sys.stderr) 
       elif self._stderr is not None: 
        try: 
         print((
          "Exception in thread " + self.name + 
          " (most likely raised during interpreter shutdown):"), file=self._stderr) 
         print((
          "Traceback (most recent call last):"), file=self._stderr) 
         while exc_tb: 
          print((
           ' File "%s", line %s, in %s' % 
           (exc_tb.tb_frame.f_code.co_filename, 
            exc_tb.tb_lineno, 
            exc_tb.tb_frame.f_code.co_name)), file=self._stderr) 
          exc_tb = exc_tb.tb_next 
         print(("%s: %s" % (exc_type, exc_value)), file=self._stderr) 
        finally: 
         del exc_type, exc_value, exc_tb 
      finally: 
       pass 
     finally: 
      with threading._active_limbo_lock: 
       try: 
        del threading._active[threading.get_ident()] 
       except: 
        pass 

    @property 
    def returned(self): 
     if self.__value is None: 
      self.join() 
     if self.__value is not None: 
      valid, value = self.__value 
      if valid: 
       return value 
      raise value 


if __name__ == '__main__': 
    main()