【发布时间】:2018-08-20 15:28:59
【问题描述】:
上下文
我需要使用多线程进行计算。我使用 SBCL,可移植性不是问题。我知道bordeaux-threads 和lparallel 存在,但我想在特定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 结果并返回结果列表res-list。这是我使用找到的资源得出的结论(见下文)。
(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
什么困扰着我
我给出的示例运行良好且功能强大(即结果不会在线程之间混淆,并且我没有遇到崩溃)。速度增益也在那里,并且计算确实在我测试过这段代码的机器上使用了几个内核/线程。但有几件事我想就以下几点提出意见/帮助:
- 参数列表
llarg和larg-temp的使用。这真的有必要吗?有什么方法可以避免操纵可能很大的列表? - 线程按照它们在
thread-list中的存储顺序进行连接。我想如果每个操作都需要不同的时间来完成,这将不是最佳的。有没有办法在完成后加入每个线程,而不是等待?
答案应该在我已经找到的资源中,但我发现更高级的东西很难解决。
目前找到的资源
【问题讨论】:
-
有没有办法在每个线程完成时加入它,而不是等待?:为什么?这对主线程的执行时间没有重大影响:在所有情况下,您都将等到最慢的线程完成。您的主线程的执行时间是每个线程执行时间的最大值(加上簿记开销)。
-
在我有多批计算要执行的情况下,我不想等待整个批次完成再开始另一批(如果每个计算都独立于其他计算) .但我想答案在于使用渠道或现有库。
标签: multithreading common-lisp sbcl