multithreading - 在 SBCL 中进行多线程计算的正确方法

标签 multithreading common-lisp sbcl

上下文

我需要使用多线程进行计算。我使用 SBCL,可移植性不是问题。我知道 bordeaux-threadslparallel 存在,但我想在特定 SBCL 线程实现提供的相对较低的级别上实现一些东西。我需要最大的速度,即使以牺牲可读性/编程工作量为代价。

计算密集型操作示例

我们可以定义一个足够计算密集型的函数,它将受益于多线程。

(defun intensive-sqrt (x)
  "Dummy calculation for intensive algorithm.
Approx 50 ms for 1e6 iterations."
  (let ((y x))
    (dotimes (it 1000000 t)
      (if (> y 1.01d0)
          (setf y (sqrt y))
          (setf y (* y y y))))
    y))

将每个计算映射到一个线程并执行

给定一个参数列表列表 llarg 和一个函数 fun,我们想要计算 nthreads 个结果并返回结果列表 资源列表。这是我使用找到的资源得出的结论(见下文)。

(defmacro splice-arglist-help (fun arglist)
  "Helper macro.
   Splices a list 'arglist' (arg1 arg2 ...) into the function call of 'fun'
   Returns (funcall fun arg1 arg2 ...)"
  `(funcall ,fun ,@arglist))

(defun splice-arglist (fun arglist)
  (eval `(splice-arglist-help ,fun ,arglist)))

(defun maplist-fun-multi (fun llarg nthreads)
  "Maps 'fun' over list of argument lists 'llarg' using multithreading.
   Breaks up llarg and feeds it to each thread.
   Appends all the result lists at the end."
  (let ((thread-list nil)
        (res-list nil))
    ;; Create and run threads
    (dotimes (it nthreads t)
      (let ((larg-temp (elt llarg it)))
        (setf thread-list (append thread-list
                                  (list (sb-thread:make-thread
                                         (lambda ()
                                           (splice-arglist fun larg-temp))))))))
    ;; Join threads
    ;; Threads are joined in order, not optimal for speed.
    ;; Should be joined when finished ?
    (dotimes (it (list-length thread-list) t)
      (setf res-list (append res-list (list (sb-thread:join-thread (elt thread-list it))))))
    res-list))

nthreads 不一定与 llarg 的长度匹配,但为了示例简单起见,我避免了额外的簿记。我还省略了用于优化的各种declare

我们可以测试多线程并比较时序:

(defparameter *test-args-sqrt-long* nil)
(dotimes (it 10000 t)
  (push (list (+ 3d0 it)) *test-args-sqrt-long*))

(time (intensive-sqrt 5d0))
(time (maplist-fun-multi #'intensive-sqrt *test-args-sqrt-long* 100))

线程数相当多。我认为最佳方法是使用与 CPU 一样多的线程,但我注意到就时间/操作而言,性能下降几乎不明显。执行更多操作需要将输入列表分解成更小的部分。

以上代码在 2 核/4 线程机器上输出:

Evaluation took:
  0.029 seconds of real time
  0.015625 seconds of total run time (0.015625 user, 0.000000 system)
  55.17% CPU
  71,972,879 processor cycles
  22,151,168 bytes consed

Evaluation took:
  1.415 seconds of real time
  4.703125 seconds of total run time (4.437500 user, 0.265625 system)
  [ Run times consist of 0.205 seconds GC time, and 4.499 seconds non-GC time. ]
  332.37% CPU
  3,530,632,834 processor cycles
  2,215,345,584 bytes consed

我在烦恼什么

我给出的示例工作得很好并且很健壮(即结果不会在线程之间混淆,而且我没有遇到崩溃)。速度增益也在那里,计算确实在我测试过这段代码的机器上使用了多个内核/线程。但有几件事我希望得到意见/帮助:

  1. 参数列表llarglarg-temp 的使用。这真的有必要吗?有什么方法可以避免操纵可能庞大的列表?
  2. 线程按照它们在thread-list 中的存储顺序加入。我想如果每个操作都需要不同的时间来完成,这将不是最佳选择。有没有办法在每个线程完成时加入,而不是等待?

答案应该在我已经找到的资源中,但我发现更高级的东西很难理解。

目前找到的资源

最佳答案

文体问题

  • splice-arglist 助手根本不需要(所以我也将跳过其中的细节)。在线程函数中使用 apply 代替:

    (lambda ()
      (apply fun larg-temp))
    
  • 您不需要(也不应该)对列表进行索引,因为每次查找都是 O(n) — 您的循环是二次的。使用 dolist 进行简单的副作用循环,或者当你有 e 时使用 loop。 G。并行迭代:

    (loop :repeat nthreads
          :for args :in llarg
          :collect (sb-thread:make-thread (lambda () (apply fun args))))
    
  • 要在创建相同长度的新列表时遍历列表,其中每个元素都是根据源列表中的相应元素计算的,请使用 mapcar:

    (mapcar #'sb-thread:join-thread threads)
    

你的函数因此变成:

(defun map-args-parallel (fun arglists nthreads)
  (let ((threads (loop :repeat nthreads
                       :for args :in arglists
                       :collect (sb-thread:make-thread
                                 (lambda ()
                                   (apply fun args))))))
    (mapcar #'sb-thread:join-thread threads)))

性能

您是对的,一个人通常只创建与 ca 一样多的线程。可用的核心数。如果您通过始终创建 n 个线程来测试性能,然后加入它们,然后转到下一批,您的性能确实不会有太大差异。那是因为效率低下在于创建线程。线程与进程一样占用大量资源。

人们通常做的是创建一个线程池,其中的线程不会被加入,而是被重用。为此,您需要一些其他机制来传达参数和结果,例如。 G。 channel (例如来自 chanl)。

但是请注意,e。 G。 lparallel 已经提供了一个 pmap 函数,而且它做的很对。此类包装器库的目的不仅是为用户(程序员)提供漂亮的界面,而且还需要认真思考问题并进行明智的优化。我非常有信心 pmap 会比您的尝试快得多。

关于multithreading - 在 SBCL 中进行多线程计算的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51934045/

相关文章:

common-lisp - 为什么应用大表上会引发CONTROL-STACK-EXHAUSTED-ERROR?

linux - 同一个进程的线程可以跑在不同的核上吗?

ubuntu - 无法使用 UFFI 加载 libncurses

emacs - 使 Emacs/Slime/Quicklisp/SBCL 在 Windows 中工作

Emacs+Slime lower-lisp 异常退出,代码为 5

recursion - 拆分列表的 Lisp 递归

c++ - 如何处理 std::thread 中的 PostMessage 线程消息?

java - ThreadPoolExecutor.execute(Runnable command) 何时创建新线程

java - Thread 中的 join() 方法是否保证完美工作,还是也依赖于各个 JVM?

lisp - 将 mapcar 映射到两个参数