Python スレッドでの実装(並列処理)

Pythonでの並列処理で扱うモジュールを2つ紹介
・threadingモジュール
・concurrent.futuresモジュール


threading


threadingで使える関数


start()
スレッドを開始
setName()
スレッドに名前をつける
getName()
スレッドの名前を取得
setDeamon(True)
スレッドをデーモンにする
join()
スレッドの処理が終わるまで待機する
run()
スレッドの処理をマニュアルで実行する



sumple.py

from time import sleep
import threading

#実行したい関数
def any():
  print("a")
  sleep(1)
  print("b")
  sleep(1)
  print("c")
  sleep(1)

def sum():
  print("a")
  sleep(1)
  print("b")
  sleep(1)
  print("c")
  sleep(1)

#関数をターゲットにスレッドを作る
t1 = threading.Thread(target=any)
t2 = threading.Thread(target=sum)

#スレッドを開始する
t1.start()
ts.start()

#スレッドの処理が終わるまで待機
t1.join()
t2.join()





スレッドを継承してrunメソッドをカスタマイズ

from time import sleep
import threading

class MyThread(threading.Thread):
  def __init__(self,n):
    super(MyThread,self).__init__()
    self.n = n
     
  def run(self):
    print("a")
    sleep(1)
    print("b")
    sleep(1)
    print("c")
    sleep(1)

t1 = MyThread("t1")
t2 = MyThread("t2")

t1.start()
t2.start()


参考サイト


concurrent.futures


sumple.py

from concurrent.futures import ThreadPoolExecutor

#3個のスレッド作成
tpe = ThreadPoolExecutor(max_workers=3)

def subti():
  link = i.get_attribute("href")
  if re.match(r".*categories$",link):
    subtitles.append(link)
    print(len(subtitles))

#メソッドを渡す
for i in contents:
  tpe.submit(subti)

#スレッド終了
tpe.shutdown()


スクレイピングをするときに必須の並列処理です。
使いこなせるようにしましょう。



スクレイピング使用例

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
options = Options()
options.add_argument('--headless')
from time import sleep
import chromedriver_binary 

def scrayping(url):
  d = webdriver.Chrome()
  d.get(url)
   
  #スクレイピング処理
   
  d.close()
   
link = [
  "https://~~",
  "https://~~",
  "https://~~",
]

#max_workersが最大の並列処理の実行できる数
#maz_workers=3だと並列処理を3個行う

executor = concurrent.futures.TreadPoolExecutor(max_workers=3)
for url in link:
  executor.submit(scrayping,url)