Skip to main content
 首页 » 编程设计

multithreading之我怎样才能在MATLAB中 'tell'每个CPU核心做什么

2025年05月04日200cyq1162

我想创建 4 个线程,并为每个线程单独编写代码,而不是 parfor 循环。其语法是什么?

请您参考如下方法:

这里有两个选择。第一个是使用parfeval您可以在其中请求多个独立的函数评估,如下所示:

% The following line executes 
% out = a(a1, a2, a3) on a worker. (The number 1 is the 
% the number of outputs requested from the function evaluation) 
% The results can be obtained using 
% out = fetchOutputs(f_a); 
f_a = parfeval(@a, 1, a1, a2, a3); 
 
% and so on... 
f_b = parfeval(@b, 1, b1, b2); 
f_c = parfeval(@c, 1, c1); 
f_d = parfeval(@d, 1, d1, d2); 

您可以使用fetchOutputs(f_a)等检索结果。

另一种选择是使用 spmd ,如下所示:

spmd 
    switch labindex 
      case 1 
        a(); 
      case 2 
        b(); 
      ... 
    end 
end 

一般来说,对于独立任务,我建议使用 parfeval,因为这种方法不依赖于并行池中的工作线程数量,而 spmd 方法则依赖于并行池中的工作线程数量。