通过IDL多线程,进行两个数相加为例
1. 相加函数如下
function add, a, b
return, a+b
end
2. 主线程函数如下,通过新建分线程调用相加函数,如果线程运行结束,则输出结果
pro thread_test
compile_opt idl2
this_pro_path = file_dirname(routine_filepath())
function_position = this_pro_path + 'add.pro'
a = [2,3,4]
b = [20,30,40]
thread_arr = objarr(3)
thread_count = n_elements(thread_arr)
for i = 0, thread_count - 1 do begin
thread = obj_new("IDL_IDLBridge")
thread->execute,".compile '" + function_position + "'"; 编译add.pro代码
thread->setvar,'a', a[i]
thread->setvar,'b', b[i]
thread->execute, "c = add(a, b)", /NOWAIT
print, 'Running... Thread ' + strtrim(i+1, 2)
thread_arr[i] = thread
endfor
stops_arr = intarr(thread_count) ; 存储线程是否运行结束, 1:已经结束, 0:没有结束
while 1 gt 0 do begin
; 判断是否所有线程运行结束
if total(stops_arr) eq thread_count then begin
print, 'Completed!'
break
endif
; 判断并修改线程运行状态,同时输出运行结果
for i = 0, thread_count-1 do begin
thread = thread_arr[i]
is_stops = stops_arr[i]
if is_stops eq 0 and thread->status() eq 0 then begin
stops_arr[i] = 1
print, 'Stops... Thread ' + strtrim(i+1, 2)
c = thread->getvar('c')
print, 'c= ' + strtrim(c, 2)
endif
endfor
endwhile
end
3. IDL运行结果如下
% Compiled module: THREAD_TEST.
Running... Thread 1
Running... Thread 2
Running... Thread 3
Stops... Thread 1
c= 22
Stops... Thread 2
c= 33
Stops... Thread 3
c= 44
Completed!