• Python有了concurrent的话mutiprocessing和threading还有存在的意义吗?


    Python3.2中引入的concurrent非常的好用,只用几行代码就可以编写出线程池/进程池,并且计算型任务效率和mutiprocessing.pool提供的poll和ThreadPoll相比不分伯仲,而且在IO型任务由于引入了Future的概念效率要高数倍。

    而threading的话还要自己维护相关的队列防止死锁,代码的可读性也会下降,相反concurrent提供的线程池却非常的便捷,不用自己操心死锁以及编写线程池代码,由于异步的概念IO型任务也更有优势。

    既然如此,如果不是为了向下兼容2.x,是不是可以完全没有必要继续使用mutiprocessing和threading了?concurrent如此的优秀。

    concurrent的确很好用,主要提供了ThreadPoolExecutor和ProcessPoolExecutor。一个多线程,一个多进程。但concurrent本质上都是对threading和mutiprocessing的封装。看它的源码可以知道。
    ThreadPoolExecutor自己提供了任务队列,不需要自己写了。而所谓的线程池,它只是简单的比较当前的threads数量和定义的max_workers的大小,小于max_workers就允许任务创建线程执行任务。可以看源码

    def _adjust_thread_count(self):
        # When the executor gets lost, the weakref callback will wake up
        # the worker threads.
        def weakref_cb(_, q=self._work_queue):
            q.put(None)
        # TODO(bquinlan): Should avoid creating new threads if there are more
        # idle threads than items in the work queue.
        if len(self._threads) < self._max_workers:
            t = threading.Thread(target=_worker,
                                 args=(weakref.ref(self, weakref_cb),
                                       self._work_queue))
            t.daemon = True
            t.start()
            self._threads.add(t)
            _threads_queues[t] = self._work_queue
      

    所以如果你自己维护队列的话也没问题,cocurrent内部也是自己维护了一个队列,它给你写好了而已。
    至于死锁问题concurrent也会引起死锁的问题。给你一个例子,运行看看

    import time
    from concurrent.futures import ThreadPoolExecutor
    
    def wait_on_b():
        time.sleep(5)
        print(b.result()) # b will never complete because it is waiting on a.
        return 5
    
    def wait_on_a():
        time.sleep(5)
        print(a.result()) # a will never complete because it is waiting on b.
        return 6
    
    
    executor = ThreadPoolExecutor(max_workers=2)
    a = executor.submit(wait_on_b)
    b = executor.submit(wait_on_a)

    ProcessPoolExecutor 内部也是使用的mutiprocessing。能够从充分利用多核的特性,摆脱GIL的限制。注意定义ProcessPoolExecutor(max_workers=2)的时候max_workers稍大于CPU的核数,不能太大。ProcessPoolExecutor内部维持了一个call_queue用于保持任务队列,其类型是multiprocessing.Queue。还有一个管理队列的线程。这可以说是cocurrent的一个优化。
    具体可以看源码,self._adjust_process_count()其实就是开启进程执行任务,点进去_adjust_process_count一看就知道。self._queue_management_thread是管理队列的线程

    if self._queue_management_thread is None:
                # Start the processes so that their sentinels are known.
                self._adjust_process_count()
                self._queue_management_thread = threading.Thread(
                        target=_queue_management_worker,
                        args=(weakref.ref(self, weakref_cb),
                              self._processes,
                              self._pending_work_items,
                              self._work_ids,
                              self._call_queue,
                              self._result_queue))
                self._queue_management_thread.daemon = True
                self._queue_management_thread.start()
                _threads_queues[self._queue_management_thread] = self._result_queue

    所以说cocurrent好用,就是它自己做了一些更好的处理,譬如维持队列,管理队列线程,不需要你再操心。当然你也可以自己实现。你能用cocurrent实现的。用threading和mutiprocessing都能实现,大不了自己再做些额外的工作。因为cocurrent本质上核心也是用的这2个。当然有了现成的更好的cocurrent最好了,直接拿来使用,省的自己再造轮子。所以说用哪个看个人熟悉程度,譬如我用的python2,就用不了cocurrent。只好用threading。

  • 相关阅读:
    4.2.1 B
    4.1.1 A
    C
    A
    排序(sort qsort)
    晕,
    clipssubviews = clipstobounds
    scrollview once more,滑出来的 刚好等于 上下偏移的,
    关于 层的显示,
    水倒过来,倒过去,穷折腾啊,
  • 原文地址:https://www.cnblogs.com/tcppdu/p/10546939.html
Copyright © 2020-2023  润新知