【问题标题】:How to get the returned value from a function after using Threading? [duplicate]使用线程后如何从函数中获取返回值? [复制]
【发布时间】:2019-10-13 05:22:27
【问题描述】:

我用python做了一个程序,可以得到类似电影的名字。我使用线程来确保函数并行运行以防止浪费时间。

import threading
import requests
from bs4 import BeautifulSoup
url = "https://www.movie-map.com/twilight.html"
url2 = "https://www.movie-map.com/Interstellar.html"
x = ''
word_list = []
def spider(url):
    word_list = []
    try:
        source_code = requests.get(url)
        plain_text =  source_code.text
        soup = BeautifulSoup(plain_text, features="lxml")
        for link in soup.find('div', attrs = {'id':'gnodMap'}):
            title = link.string
            word_list.append(title)
    except:
        pass
    x = word_list
    return word_list

t1 = threading.Thread(target=spider, args=[url])
t2 = threading.Thread(target=spider, args=[url2])
t1.start()
t2.start()

我应该如何从函数中获取返回值?

【问题讨论】:

  • 你指的是哪个函数?

标签: python multithreading parallel-processing


【解决方案1】:

可能最简单的方法是通过queue.Queue 类。

import queue
import threading


q = queue.Queue()
t = threading.Thread(target=lambda: q.put('Hello!'))
t.start()

print(q.get(timeout=5))  # "Hello!"

您还可以使用threading.Lock 来同步对变量的共享访问,如下所示:

import time


class Links(object):

    def __init__(self):
        self._lock = threading.Lock()
        self._links = []

    @property
    def links(self):
        self._lock.acquire()
        links = list(self._links)
        self._lock.release()
        return links

    def add(self, link):
        self._lock.acquire()
        self._links.append(link)
        self._lock.release()


l = Links()


def target():
    time.sleep(2)
    l.add('link')


t = threading.Thread(target=target)
t.start()

print(l.links) # []
time.sleep(2)
print(l.links) # ['link']

【讨论】:

    猜你喜欢
    • 2018-10-21
    • 1970-01-01
    • 1970-01-01
    • 2014-02-12
    • 2016-01-09
    • 2017-08-08
    • 2020-11-09
    • 2015-01-14
    • 2011-10-17
    相关资源
    最近更新 更多