The name of the Python thread is not output.

Asked 2 years ago, Updated 2 years ago, 23 views

# -*- 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()

When you create a thread, you passed the name to the constructor in the form name=XXX but when you call current_thread().getName() within the function, only MainThread appears.

How do I output the name of a thread running a specific function?

python

2022-09-22 18:18

1 Answers

You set the wrong target when creating the thread.

thread1 = threading.Thread(target=find_wiki_links(), name="thread1")
thread2 = threading.Thread(target=find_wiki_links(), name="thread2")

Not

thread1 = threading.Thread(target=find_wiki_links, name="thread1")
thread2 = threading.Thread(target=find_wiki_links, name="thread2")

You need to modify it to . Do not use parentheses when specifying a function in target= ㅜ<


2022-09-22 18:18

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.