2017-01-11 11 views
0

私はPython-Threadingの初心者です。複数の投稿を行ってきましたが、実際にどのように使用するのか分かりませんでした。しかし、私は自分の仕事を完了しようとしました、そして、私は正しいアプローチでそれをやっているかどうかチェックしたいと思います。Python Fireマルチスレッドを使用した動的URL

タスク: 約20K個のレコードを含む大きなCSVを読み込み、各レコードからIDを取得し、CSVの各レコードのHTTP API呼び出しを開始します。

t1 = time.time() 
file_data_obj = csv.DictReader(open(file_path, 'rU')) 
threads = [] 
for record in file_data_obj: 
     apiurl = https://www.api-server.com?id=record.get("acc_id", "") 
     thread = threading.Thread(target=requests.get, args=(apiurl,)) 
     thread.start() 
     threads.append(thread) 

t2 = time.time() 

for thread in threads: 
    thread.join() 

print("Total time required to process a file - {} Secs".format(t2-t1)) 
  • 20Kレコードがあるとして、それは20Kのスレッドを起動しますか? OR OS/Pythonこれを処理しますか?はいの場合は制限できますか?
  • requests.getが返す応答を収集するにはどうすればよいですか?
  • t2 - t1は実際にファイル全体を処理するのに必要な時間をmwにしますか?

答えて

1

20Kレコードがあるので、20Kスレッドを開始しますか? OR OS/Pythonがそれを処理しますか?はいの場合は制限できますか?

はい - 繰り返しごとにスレッドを開始します。最大スレッド数はOSに依存します。

どのようにrequest.getによって返された応答を取得できますか?

threadingモジュールのみを使用する場合は、Queueを使用する必要があります。 ThreadsNoneを返すので、Threadmainの間の通信回線を実装する必要があります。

from queue import Queue 
from threading import Thread 
import time 

# A thread that produces data 
q = Queue() 



def return_get(q, apiurl): 
    q.put(requests.get(apiurl) 

for record in file_data_obj: 
    apiurl = https://www.api-server.com?id=record.get("acc_id", "") 
    t = threading.Thread(target=return_get, args=(q, apiurl)) 
    t.start() 
    threads.append(t) 

for thread in threads: 
    thread.join() 

while not q.empty: 
    r = q.get() # Fetches the first item on the queue 
    print(r.text) 

代わりに、ワーカープールを使用することもできます。

from concurrent.futures import ThreadPoolExecutor 
from queue import Queue 
import urllib.request 

threads = [] 

pool = ThreadPoolExecutor(10) 

# Submit work to the pool 
for record in file_data_obj: 
    apiurl = https://www.api-server.com?id=record.get("acc_id", "") 
    t = pool.submit(fetch_url, 'http://www.python.org') 
    threads.append(t) 

for t in threads: 
    print(t.result()) 
1

あなたは

def load_url(url, timeout): 
    with urllib.request.urlopen(url, timeout=timeout) as conn: 
     return conn.read() 

Nの労働者とプールのexecutorを作成し、単一のページを取得しThreadPoolExecutor

を使用し、URLや内容を報告することができ

with concurrent.futures.ThreadPoolExecutor(max_workers=N_workers) as executor: 
    # Start the load operations and mark each future with its URL 
    future_to_url = {executor.submit(load_url, url, 60): url for url in URLS} 
    for future in concurrent.futures.as_completed(future_to_url): 
     url = future_to_url[future] 
     try: 
      data = future.result() 
     except Exception as exc: 
      print('%r generated an exception: %s' % (url, exc)) 
     else: 
      print('%r page is %d bytes' % (url, len(data))) 
関連する問題