파이썬 쓰레드의 이름이 출력되지 않습니다.
조회수 582회
# -*- coding: utf-8 -*-
from urllib.request import urlopen
from bs4 import BeautifulSoup
import threading
import re
html = urlopen("https://en.wikipedia.org/wiki/PyPy")
bsObj = BeautifulSoup(html, "html.parser")
lock = threading.Lock()
def find_wiki_links():
lock.acquire()
for link in bsObj.find("div", id="bodyContent").findAll("a", href=re.compile("^(\/wiki\/)((?!:).)*$")):
if "href" in link.attrs:
print(threading.current_thread().getName(), end=": ")
print(link.attrs["href"])
lock.release()
thread1 = threading.Thread(target=find_wiki_links(), name="thread1")
thread2 = threading.Thread(target=find_wiki_links(), name="thread2")
thread1.start()
thread2.start()
쓰레드를 생성할 때 생성자에 name=XXX
형식으로 이름을 전달했는데, 막상 함수 안에서 current_thread().getName()
을 호출시켜보면 MainThread
라고만 나옵니다.
특정 함수를 실행중인 쓰레드의 이름을 출력하려면 어떻게 해야 하나요?
-
(•́ ✖ •̀)
알 수 없는 사용자
1 답변
-
Thread 생성시 target을 잘못 잡으셨네요.
thread1 = threading.Thread(target=find_wiki_links(), name="thread1") thread2 = threading.Thread(target=find_wiki_links(), name="thread2")
가 아니라
thread1 = threading.Thread(target=find_wiki_links, name="thread1") thread2 = threading.Thread(target=find_wiki_links, name="thread2")
로 수정하셔야합니다.
target =
에서 함수 지정 시 괄호를 쓰면 안돼요 ㅜㅜ- find_wiki_links() 를 써버리면, 메인쓰레드가 해당 함수를 호출합니다. 그리고 함수의 리턴값(이 경우에는 None)이 새 쓰레드에 전달되지요. Demi 2019.1.21 10:24
- 답변을 늦게 봤네요. 감사합니다. 알 수 없는 사용자 2019.1.22 19:29
댓글 입력