Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 使用线程后如何从函数中获取返回值?_Python_Multithreading_Parallel Processing - Fatal编程技术网

Python 使用线程后如何从函数中获取返回值?

Python 使用线程后如何从函数中获取返回值?,python,multithreading,parallel-processing,Python,Multithreading,Parallel Processing,我用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(ur

我用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()

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

最简单的方法可能是通过类

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

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']

你指的是哪个功能?
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']