同时运行两个任务

时间:2020-09-26 04:43:19

标签: matlab multitasking

我想在MATLAB中同时运行两个任务:

任务1.无限while循环,不断记录音频数据并检测救护车并将结果存储在变量中。

任务2。同样,无限循环正在处理一些图像并提供输出。将该输出与任务1的输出进行比较,并将最终结果提供给Arduino以根据结果切换交通信号。

任务1是独立的。但是任务2需要任务1的数据,以便在检测到救护车时可以将输出提供给Arduino,并根据救护车检测执行指定的操作。

我如何同时并行执行两项任务?

1 个答案:

答案 0 :(得分:0)

正如评论中已经讨论的那样,MATLAB并不是特别适合多任务处理,尽管它具有某些功能,例如回调函数和parfor()函数,在某些情况下非常有用。一个更通用的解决方案是让操作系统为您处理多任务,因为这是大多数OS都擅长的事情。为此,您只需让MATLAB生成Task 1Task 2的子进程即可;这些子元素本身可能是对新MATLAB实例的调用,在这种情况下,您可能希望使用命令行标志-nodisplay-nodesktop -nosplash

在父MATLAB实例中,您可以调用以下函数:

function fork( command_line )
% FORK - spawn child process
% fork()  creates  an  arbitrary  child process in the background, without
% blocking the MATLAB interpreter. This is quite different from your  sys-
% tem-level fork(2), if one exists.
%
% On  *nix systems, the specified process is started as a background shell
% job. On Windows systems, a window is created for each new process.

  if isunix() || ismac() %testing ismac() is probably pointless since both ismac() and isunix() evaluate to true on Mac systems
    redirections=' >/dev/null'; %keep the terminal uncluttered (assuming stderr is seldom used)
    system(sprintf('%s%s &',command_line,redirections));
    clear redirections;
  elseif ispc()
    redirections=''; %since START below spawns a new window, there is no point in restricting stdout with >NUL:
    system(sprintf('START "%s" /MIN CMD /C "%s%s"','Forked from MATLAB',command_line,redirections));
    clear redirections;
  end
end

子进程又可以通过HDF5文件,纯文本文件,POSIX信号,Unix域套接字,TCP套接字(您似乎正在尝试使用)等相互通信。

相关问题