{"id":207,"date":"2023-02-22T22:24:09","date_gmt":"2023-02-22T14:24:09","guid":{"rendered":"https:\/\/www.appblog.cn\/?p=207"},"modified":"2023-04-30T15:28:50","modified_gmt":"2023-04-30T07:28:50","slug":"python-thread-pool-implementation","status":"publish","type":"post","link":"https:\/\/www.appblog.cn\/index.php\/2023\/02\/22\/python-thread-pool-implementation\/","title":{"rendered":"Python\u7ebf\u7a0b\u6c60\u5b9e\u73b0"},"content":{"rendered":"<p>\u5bf9\u4e8e\u4efb\u52a1\u6570\u91cf\u4e0d\u65ad\u589e\u52a0\u7684\u7a0b\u5e8f\uff0c\u6bcf\u6709\u4e00\u4e2a\u4efb\u52a1\u5c31\u751f\u6210\u4e00\u4e2a\u7ebf\u7a0b\uff0c\u6700\u7ec8\u4f1a\u5bfc\u81f4\u7ebf\u7a0b\u6570\u91cf\u7684\u5931\u63a7\uff0c\u56e0\u6b64\u56fa\u5b9a\u7ebf\u7a0b\u6570\u91cf\u7684\u7ebf\u7a0b\u6c60\u662f\u5fc5\u8981\u7684\u3002<\/p>\n<h2>threadpool\u6a21\u5757<\/h2>\n<p>Python\u7b2c\u4e09\u65b9\u6a21\u5757\uff0c\u652f\u6301Python2\u548cPython3\u3002<\/p>\n<p><!-- more --><\/p>\n<pre><code class=\"language-python\"># -*- coding: utf-8 -*-\n# pip install threadpool\nimport threadpool\nimport time\n\ndef sayHello(a):\n    print(&quot;hello: &quot; + a)\n    time.sleep(2)\n\ndef main():\n    global result\n    seed = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n    start_t = time.time()\n    task_pool = threadpool.ThreadPool(5)\n    requests = threadpool.makeRequests(sayHello, seed)\n    for req in requests:\n        task_pool.putRequest(req)\n    task_pool.wait()\n    end_t = time.time()\n    time_t = end_t - start_t\n    print(&quot;time: &quot; + str(time_t))\n    start = time.time()\n    for each in seed:\n        sayHello(each)\n    end = time.time()\n    print(&quot;time: &quot; + str(end - start))\n\nif __name__ == &#039;__main__&#039;:\n    main()<\/code><\/pre>\n<h2>future\u6a21\u5757<\/h2>\n<p>threadpool\u662f\u4e00\u4e2a\u6bd4\u8f83\u8001\u7684\u6a21\u5757\uff0c\u5df2\u7ecf\u4e0d\u518d\u662f\u4e3b\u6d41\uff0c\u5173\u4e8ePython\u591a\u7ebf\u7a0b\uff0c\u63a8\u8350future\u6a21\u5757<\/p>\n<p>\u4f7f\u7528concurrent.futures\u6a21\u5757\uff0c\u8be5\u6a21\u5757\u662fPython3\u4e2d\u81ea\u5e26\u7684\u6a21\u5757\uff0c\u4f46\u662f\uff0cPython2.7\u4ee5\u4e0a\u7248\u672c\u4e5f\u53ef\u4ee5\u5b89\u88c5\u4f7f\u7528<\/p>\n<pre><code class=\"language-python\"># -*- coding: utf-8 -*-\n# pip install futures\nfrom concurrent.futures import ThreadPoolExecutor\nimport time\n\ndef sayHello(a):\n    print(&quot;hello: &quot; + a)\n    time.sleep(2)\n\ndef main():\n    seed = [&#039;a&#039;, &#039;b&#039;, &#039;c&#039;]\n    start = time.time()\n    for each in seed:\n        sayHello(each)\n    end = time.time()\n    print(&quot;time: &quot; + str(end-start))\n    start1 = time.time()\n    with ThreadPoolExecutor(3) as executor1:\n        for each in seed:\n            executor1.submit(sayHello, each)\n    end1 = time.time()\n    print(&quot;time1: &quot; + str(end1-start1))\n    start2 = time.time()\n    with ThreadPoolExecutor(3) as executor2:\n        executor2.map(sayHello, seed)\n    end2 = time.time()\n    print(&quot;time2: &quot; + str(end2-start2))\n\nif __name__ == &#039;__main__&#039;:\n    main()<\/code><\/pre>\n<p>\u6ce8\u610f\u5230\u4e00\u70b9\uff1a<code>concurrent.futures.ThreadPoolExecutor<\/code>\u5728\u63d0\u4ea4\u4efb\u52a1\u7684\u65f6\u5019\uff0c\u6709\u4e24\u79cd\u65b9\u5f0f\uff1a\u4e00\u79cd\u662f<code>submit()<\/code>\u51fd\u6570\uff0c\u53e6\u4e00\u79cd\u662f<code>map()<\/code>\u51fd\u6570\uff0c\u4e24\u8005\u7684\u4e3b\u8981\u533a\u522b\u5728\u4e8e\uff1a<\/p>\n<ol>\n<li>map\u53ef\u4ee5\u4fdd\u8bc1\u8f93\u51fa\u7684\u987a\u5e8f\uff0csubmit\u8f93\u51fa\u7684\u987a\u5e8f\u662f\u4e71\u7684<\/li>\n<li>\u5982\u679c\u63d0\u4ea4\u7684\u4efb\u52a1\u51fd\u6570\u662f\u4e00\u6837\u7684\uff0c\u5c31\u53ef\u4ee5\u7b80\u5316\u6210map\u3002\u4f46\u662f\u5047\u5982\u63d0\u4ea4\u7684\u4efb\u52a1\u51fd\u6570\u662f\u4e0d\u4e00\u6837\u7684\uff0c\u6216\u8005\u6267\u884c\u7684\u8fc7\u7a0b\u53ef\u80fd\u51fa\u73b0\u5f02\u5e38\uff08\u4f7f\u7528map\u6267\u884c\u8fc7\u7a0b\u4e2d\u53d1\u73b0\u95ee\u9898\u4f1a\u76f4\u63a5\u629b\u51fa\u9519\u8bef\uff09\u5c31\u8981\u7528\u5230submit<\/li>\n<li>submit\u548cmap\u7684\u53c2\u6570\u662f\u4e0d\u540c\u7684\uff0csubmit\u6bcf\u6b21\u90fd\u9700\u8981\u63d0\u4ea4\u4e00\u4e2a\u76ee\u6807\u51fd\u6570\u548c\u5bf9\u5e94\u7684\u53c2\u6570\uff0cmap\u53ea\u9700\u8981\u63d0\u4ea4\u4e00\u6b21\u76ee\u6807\u51fd\u6570\uff0c\u76ee\u6807\u51fd\u6570\u7684\u53c2\u6570\u653e\u5728\u4e00\u4e2a\u8fed\u4ee3\u5668\uff08\u5217\u8868\uff0c\u5b57\u5178\uff09\u91cc\u5373\u53ef<\/li>\n<\/ol>\n<h2>\u81ea\u5b9a\u4e49\u7ebf\u7a0b\u6c60<\/h2>\n<p>\u8fd9\u91cc\u8981\u8003\u8651\u4e00\u4e2a\u95ee\u9898\uff0c\u4ee5\u4e0a\u4e24\u79cd\u7ebf\u7a0b\u6c60\u7684\u5b9e\u73b0\u90fd\u662f\u5c01\u88c5\u597d\u7684\uff0c\u4efb\u52a1\u53ea\u80fd\u5728\u7ebf\u7a0b\u6c60\u521d\u59cb\u5316\u7684\u65f6\u5019\u6dfb\u52a0\u4e00\u6b21\uff0c\u90a3\u4e48\uff0c\u5047\u8bbe\u6211\u73b0\u5728\u6709\u8fd9\u6837\u4e00\u4e2a\u9700\u6c42\uff0c\u9700\u8981\u5728\u7ebf\u7a0b\u6c60\u8fd0\u884c\u65f6\uff0c\u518d\u5f80\u91cc\u9762\u6dfb\u52a0\u65b0\u7684\u4efb\u52a1\uff08\u6ce8\u610f\uff0c\u662f\u65b0\u4efb\u52a1\uff0c\u4e0d\u662f\u65b0\u7ebf\u7a0b\uff09\uff0c\u90a3\u4e48\u8981\u600e\u4e48\u529e\uff1f<\/p>\n<p>\u5176\u5b9e\u6709\u4e24\u79cd\u65b9\u5f0f\uff1a<\/p>\n<h3>\u91cd\u5199threadpool\u6216\u8005future\u7684\u51fd\u6570<\/h3>\n<p>\u8fd9\u4e2a\u65b9\u6cd5\u9700\u8981\u9605\u8bfb\u6e90\u6a21\u5757\u7684\u6e90\u7801\uff0c\u5fc5\u987b\u641e\u6e05\u695a\u6e90\u6a21\u5757\u7ebf\u7a0b\u6c60\u7684\u5b9e\u73b0\u673a\u5236\u624d\u80fd\u6b63\u786e\u7684\u6839\u636e\u81ea\u5df1\u7684\u9700\u8981\u91cd\u5199\u5176\u4e2d\u7684\u65b9\u6cd5\u3002<\/p>\n<h3>\u81ea\u5df1\u6784\u5efa\u4e00\u4e2a\u7ebf\u7a0b\u6c60<\/h3>\n<p>\u8fd9\u4e2a\u65b9\u6cd5\u5c31\u9700\u8981\u5bf9\u7ebf\u7a0b\u6c60\u7684\u6709\u4e00\u4e2a\u6e05\u6670\u7684\u4e86\u89e3\uff0c\u53c2\u8003\uff1a<a target=\"_blank\" rel=\"noopener\" href=\"https:\/\/github.com\/iyezhou\/python_spider\">https:\/\/github.com\/iyezhou\/python_spider<\/a><\/p>\n<pre><code class=\"language-python\"># -*- coding: utf-8 -*-\n\nimport threading\nimport Queue\nimport hashlib\nimport logging\nfrom utils.progress import PrintProgress\nfrom utils.save import SaveToSqlite\n\nclass ThreadPool(object):\n    def __init__(self, thread_num, args):\n\n        self.args = args\n        self.work_queue = Queue.Queue()\n        self.save_queue = Queue.Queue()\n        self.threads = []\n        self.running = 0\n        self.failure = 0\n        self.success = 0\n        self.tasks = {}\n        self.thread_name = threading.current_thread().getName()\n        self.__init_thread_pool(thread_num)\n\n    # \u7ebf\u7a0b\u6c60\u521d\u59cb\u5316\n    def __init_thread_pool(self, thread_num):\n        # \u4e0b\u8f7d\u7ebf\u7a0b\n        for i in range(thread_num):\n            self.threads.append(WorkThread(self))\n        # \u6253\u5370\u8fdb\u5ea6\u4fe1\u606f\u7ebf\u7a0b\n        self.threads.append(PrintProgress(self))\n        # \u4fdd\u5b58\u7ebf\u7a0b\n        self.threads.append(SaveToSqlite(self, self.args.dbfile))\n\n    # \u6dfb\u52a0\u4e0b\u8f7d\u4efb\u52a1\n    def add_task(self, func, url, deep):\n        # \u8bb0\u5f55\u4efb\u52a1\uff0c\u5224\u65ad\u662f\u5426\u5df2\u7ecf\u4e0b\u8f7d\u8fc7\n        url_hash = hashlib.new(&#039;md5&#039;, url.encode(&quot;utf8&quot;)).hexdigest()\n        if not url_hash in self.tasks:\n            self.tasks[url_hash] = url\n            self.work_queue.put((func, url, deep))\n            logging.info(&quot;{0} add task {1}&quot;.format(self.thread_name, url.encode(&quot;utf8&quot;)))\n\n    # \u83b7\u53d6\u4e0b\u8f7d\u4efb\u52a1\n    def get_task(self):\n        # \u4ece\u961f\u5217\u91cc\u53d6\u5143\u7d20\uff0c\u5982\u679cblock=True,\u5219\u4e00\u76f4\u963b\u585e\u5230\u6709\u53ef\u7528\u5143\u7d20\u4e3a\u6b62\u3002\n        task = self.work_queue.get(block=False)\n\n        return task\n\n    def task_done(self):\n        # \u8868\u793a\u961f\u5217\u4e2d\u7684\u67d0\u4e2a\u5143\u7d20\u5df2\u7ecf\u6267\u884c\u5b8c\u6bd5\u3002\n        self.work_queue.task_done()\n\n    # \u5f00\u59cb\u4efb\u52a1\n    def start_task(self):\n        for item in self.threads:\n            item.start()\n\n        logging.debug(&quot;Work start&quot;)\n\n    def increase_success(self):\n        self.success += 1\n\n    def increase_failure(self):\n        self.failure += 1\n\n    def increase_running(self):\n        self.running += 1\n\n    def decrease_running(self):\n        self.running -= 1\n\n    def get_running(self):\n        return self.running\n\n    # \u6253\u5370\u6267\u884c\u4fe1\u606f\n    def get_progress_info(self):\n        progress_info = {}\n        progress_info[&#039;work_queue_number&#039;] = self.work_queue.qsize()\n        progress_info[&#039;tasks_number&#039;] = len(self.tasks)\n        progress_info[&#039;save_queue_number&#039;] = self.save_queue.qsize()\n        progress_info[&#039;success&#039;] = self.success\n        progress_info[&#039;failure&#039;] = self.failure\n\n        return progress_info\n\n    def add_save_task(self, url, html):\n        self.save_queue.put((url, html))\n\n    def get_save_task(self):\n        save_task = self.save_queue.get(block=False)\n\n        return save_task\n\n    def wait_all_complete(self):\n        for item in self.threads:\n            if item.isAlive():\n                # join\u51fd\u6570\u7684\u610f\u4e49\uff0c\u53ea\u6709\u5f53\u524d\u6267\u884cjoin\u51fd\u6570\u7684\u7ebf\u7a0b\u7ed3\u675f\uff0c\u7a0b\u5e8f\u624d\u80fd\u63a5\u7740\u6267\u884c\u4e0b\u53bb\n                item.join()\n\n# WorkThread \u7ee7\u627f\u81eathreading.Thread\nclass WorkThread(threading.Thread):\n    # \u8fd9\u91cc\u7684thread_pool\u5c31\u662f\u4e0a\u9762\u7684ThreadPool\u7c7b\n    def __init__(self, thread_pool):\n        threading.Thread.__init__(self)\n        self.thread_pool = thread_pool\n\n    # \u5b9a\u4e49\u7ebf\u7a0b\u529f\u80fd\u65b9\u6cd5\uff0c\u5373\uff0c\u5f53thread_1\uff0c...\uff0cthread_n\uff0c\u8c03\u7528start\uff08\uff09\u4e4b\u540e\uff0c\u6267\u884c\u7684\u64cd\u4f5c\u3002\n    def run(self):\n        print (threading.current_thread().getName())\n        while True:\n            try:\n                # get_task()\u83b7\u53d6\u4ece\u5de5\u4f5c\u961f\u5217\u91cc\u83b7\u53d6\u5f53\u524d\u6b63\u5728\u4e0b\u8f7d\u7684\u7ebf\u7a0b\uff0c\u683c\u5f0f\u4e3afunc,url,deep\n                do, url, deep = self.thread_pool.get_task()\n                self.thread_pool.increase_running()\n\n                # \u5224\u65addeep\uff0c\u662f\u5426\u83b7\u53d6\u65b0\u7684\u94fe\u63a5\n                flag_get_new_link = True\n                if deep &gt;= self.thread_pool.args.deep:\n                    flag_get_new_link = False\n\n                # \u6b64\u5904do\u4e3a\u5de5\u4f5c\u961f\u5217\u4f20\u8fc7\u6765\u7684func\uff0c\u8fd4\u56de\u503c\u4e3a\u4e00\u4e2a\u9875\u9762\u5185\u5bb9\u548c\u8fd9\u4e2a\u9875\u9762\u4e0a\u6240\u6709\u7684\u65b0\u94fe\u63a5\n                html, new_link = do(url, self.thread_pool.args, flag_get_new_link)\n\n                if html == &#039;&#039;:\n                    self.thread_pool.increase_failure()\n                else:\n                    self.thread_pool.increase_success()\n                    # html\u6dfb\u52a0\u5230\u5f85\u4fdd\u5b58\u961f\u5217\n                    self.thread_pool.add_save_task(url, html)\n\n                # \u6dfb\u52a0\u65b0\u4efb\u52a1\uff0c\u5373\uff0c\u5c06\u65b0\u9875\u9762\u4e0a\u7684\u4e0d\u91cd\u590d\u7684\u94fe\u63a5\u52a0\u5165\u5de5\u4f5c\u961f\u5217\u3002\n                if new_link:\n                    for url in new_link:\n                        self.thread_pool.add_task(do, url, deep + 1)\n\n                self.thread_pool.decrease_running()\n                # self.thread_pool.task_done()\n            except Queue.Empty:\n                if self.thread_pool.get_running() &lt;= 0:\n                    break\n            except Exception, e:\n                self.thread_pool.decrease_running()\n                # print str(e)\n                break<\/code><\/pre>\n","protected":false},"excerpt":{"rendered":"<p>\u5bf9\u4e8e\u4efb\u52a1\u6570\u91cf\u4e0d\u65ad\u589e\u52a0\u7684\u7a0b\u5e8f\uff0c\u6bcf\u6709\u4e00\u4e2a\u4efb\u52a1\u5c31\u751f\u6210\u4e00\u4e2a\u7ebf\u7a0b\uff0c\u6700\u7ec8\u4f1a\u5bfc\u81f4\u7ebf\u7a0b\u6570\u91cf\u7684\u5931\u63a7\uff0c\u56e0\u6b64\u56fa\u5b9a\u7ebf\u7a0b\u6570\u91cf\u7684\u7ebf\u7a0b\u6c60\u662f\u5fc5 [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79],"tags":[],"class_list":["post-207","post","type-post","status-publish","format-standard","hentry","category-python"],"_links":{"self":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/207","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/comments?post=207"}],"version-history":[{"count":0,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/posts\/207\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/media?parent=207"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/categories?post=207"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.appblog.cn\/index.php\/wp-json\/wp\/v2\/tags?post=207"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}