matlab多线程,parfor循环进度,matlab互斥锁

本文介绍了在MATLAB2022b中使用parfor进行多线程计算的方法,以及如何实现parfor循环的进度条显示,包括窗口进度条和底部进度条。同时,针对parfor中的数据读写问题,通过DataQueue和afterEach方法模拟互斥锁机制,确保数据安全写入文件。此外,文中还提到parfor_progress.m函数作为parfor循环的进度监测工具。
摘要由CSDN通过智能技术生成

一. 内容简介

matlab多线程,parfor循环进度,matlab互斥锁

二. 软件环境

2.1 matlab 2022b

2.2代码链接

https://gitee.com/JJW_1601897441/csdn

三.主要流程

3.1 matlab多线程

有好几种,最简单的,最好理解的就是parfor,就拿那个为例子了,使用情况就是每一个for循环之前不能依赖关系,每轮计算都是独立的这种,才可以用parfor,不同版本不太一样,老版限制好像更多一些

parfor i = 1:1000
    disp(i);
end

在这里插入图片描述

3.2 parfor循环进度

用parfor并行去算一些东西的时候,有些需要循环很多次,我们是不清楚程序到底执行了多少轮,如果可以看到进度的话,时间太长了,我们或许就不会算了,

3.2.1 进度条窗口方式

会用就行,可以直接拷贝走,这个是官方文档里面找的

w = waitbar(0,'Please wait ...');

% Create DataQueue and listener
D = parallel.pool.DataQueue;
afterEach(D,@parforWaitbar);

N = 10000;
parforWaitbar(w,N)


parfor i = 1:N
	% pause替换乘自己的就可以了
    pause(rand)
    
    send(D,[]);
end
delete(w);

function parforWaitbar(waitbarHandle,iterations)
    persistent count h N
    if nargin == 2
        % Initialize
        
        count = 0;
        h = waitbarHandle;
        N = iterations;
    else
        % Update the waitbar
        
        % Check whether the handle is a reference to a deleted object
        if isvalid(h)
            count = count + 1;
            waitbar(count / N,h);
        end
    end
end

在这里插入图片描述

3.2.2 底部进度条方式

会用就行,也是官方网站里面找的,这个还需要一个文件,放到同一级目录就可以了,代码我放上边链接了

% 设置循环次数
N = 10000;
% 创建一个迭代计数器对象
parfor_progress(N);
parfor i = 1:N
    % pause替换乘自己的就可以了
    pause(rand)

    parfor_progress;
end
parfor_progress(0);

在这里插入图片描述

3.3 matlab互斥锁

在parfor循环中,读写数据是很麻烦的,并行计算就是要计算结果的,但是parfor中的计算结果很难接收出来,量少的时候,还可以通过数组接收(2016版不可以),量多的时候,数组接收就不太现实,每轮循环把数据写入文件中呢,parfor会报错,即使可以的话,由于matlab没有互斥锁,写文件即使可以写进去,也会是乱的,没办法用

还是那句话,会用就行,替换成自己的就可以了,注释写里面了

% 创建一个 DataQueue 对象
dq = parallel.pool.DataQueue;
file = fopen('ccc.txt','w');

% 多重匿名函数
fun_with_params = @(data) saveData(data, file);
% 在 DataQueue 上设置 afterEach 方法,
% 这个是给数据绑定一个处理方法,就是在信号发送以后,执行那个处理方法,
% 这个处理方法不是并行的,同一时刻只有一个线程在处理数据,其他的线程都要排队
% 和互斥锁的思想很像
afterEach(dq, fun_with_params);
% 在工作线程中定义处理函数并发送数据到 DataQueue
parfor i = 1:100
    % 替换成自己的
    a = rand();

    % 在这里通过 send 函数将数据发送到 DataQueue
    % 可以发送单个,也可也发送数组
    send(dq, a);
end

fclose(file);

function saveData(data, file)
    % 在此处编写后处理代码
    fprintf(file,'%.10f ', data); 
    fprintf(file,'\n'); 
end

在这里插入图片描述

3.4 parfor_progress.m

function percent = parfor_progress(N)
%PARFOR_PROGRESS Progress monitor (progress bar) that works with parfor.
%   PARFOR_PROGRESS works by creating a file called parfor_progress.txt in
%   your working directory, and then keeping track of the parfor loop's
%   progress within that file. This workaround is necessary because parfor
%   workers cannot communicate with one another so there is no simple way
%   to know which iterations have finished and which haven't.
%
%   PARFOR_PROGRESS(N) initializes the progress monitor for a set of N
%   upcoming calculations.
%
%   PARFOR_PROGRESS updates the progress inside your parfor loop and
%   displays an updated progress bar.
%
%   PARFOR_PROGRESS(0) deletes parfor_progress.txt and finalizes progress
%   bar.
%
%   To suppress output from any of these functions, just ask for a return
%   variable from the function calls, like PERCENT = PARFOR_PROGRESS which
%   returns the percentage of completion.
%
%   Example:
%
%      N = 100;
%      parfor_progress(N);
%      parfor i=1:N
%         pause(rand); % Replace with real code
%         parfor_progress;
%      end
%      parfor_progress(0);
%
%   See also PARFOR.

% By Jeremy Scheff - jdscheff@gmail.com - http://www.jeremyscheff.com/

error(nargchk(0, 1, nargin, 'struct'));

if nargin < 1
    N = -1;
end

percent = 0;
w = 50; % Width of progress bar

if N > 0
    f = fopen('parfor_progress.txt', 'w');
    if f<0
        error('Do you have write permissions for %s?', pwd);
    end
    fprintf(f, '%d\n', N); % Save N at the top of progress.txt
    fclose(f);
    
    if nargout == 0
        disp(['  0%[>', repmat(' ', 1, w), ']']);
    end
elseif N == 0
    delete('parfor_progress.txt');
    percent = 100;
    
    if nargout == 0
        disp([repmat(char(8), 1, (w+9)), char(10), '100%[', repmat('=', 1, w+1), ']']);
    end
else
    if ~exist('parfor_progress.txt', 'file')
        error('parfor_progress.txt not found. Run PARFOR_PROGRESS(N) before PARFOR_PROGRESS to initialize parfor_progress.txt.');
    end
    
    f = fopen('parfor_progress.txt', 'a');
    fprintf(f, '1\n');
    fclose(f);
    
    f = fopen('parfor_progress.txt', 'r');
    progress = fscanf(f, '%d');
    fclose(f);
    percent = (length(progress)-1)/progress(1)*100;
    
    if nargout == 0
        perc = sprintf('%3.0f%%', percent); % 4 characters wide, percentage
        disp([repmat(char(8), 1, (w+9)), char(10), perc, '[', repmat('=', 1, round(percent*w/100)), '>', repmat(' ', 1, w - round(percent*w/100)), ']']);
    end
end

3.5 补充

按下面代码执行的,afterEach只能保证传完数据以后执行对应函数,并不代表一个循环里面的都一起执行的
在这里插入图片描述

% 创建一个 DataQueue 对象
dq1 = parallel.pool.DataQueue;
dq2 = parallel.pool.DataQueue;
file1 = fopen('ccc1.txt','w');
file2 = fopen('ccc2.txt','w');
% 多重匿名函数
fun_with_params1 = @(data) saveData(data, file1);
fun_with_params2 = @(data) saveData(data, file2);
% 在 DataQueue 上设置 afterEach 方法
afterEach(dq1, fun_with_params1);
afterEach(dq2, fun_with_params2);
% 在工作线程中定义处理函数并发送数据到 DataQueue
parfor i = 1:1000
    % 替换成自己的
    a = rand();


    % 在这里通过 send 函数将数据发送到 DataQueue
    % 可以发送单个,也可也发送数组
    send(dq1, a);
    send(dq2, a);
end


% 等待所有数据接收完成


% 显示接收到的数据
% 辅助函数用于保存接收到的数据到数组
function saveData(data, file)
    % 在此处编写后处理代码
    fprintf(file,'%.10f ', data); 
    fprintf(file,'\n'); 
end


改进

% 创建一个 DataQueue 对象
dq1 = parallel.pool.DataQueue;
file1 = fopen('ccc11.txt','w');
file2 = fopen('ccc21.txt','w');
file3 = fopen('ccc31.txt','w');
% 多重匿名函数
fun_with_params1 = @(data1) saveData(data1, file1, file2,file3);
% 在 DataQueue 上设置 afterEach 方法
afterEach(dq1, fun_with_params1);
% 在工作线程中定义处理函数并发送数据到 DataQueue
parfor i = 1:100
    % 替换成自己的
    a = rand();

    data = {i,i,i}
    % 在这里通过 send 函数将数据发送到 DataQueue
    % 可以发送单个,也可也发送数组
    send(dq1, data);
end


% 等待所有数据接收完成

fclose(file1);
fclose(file2);
fclose(file3);
% 显示接收到的数据
% 辅助函数用于保存接收到的数据到数组
function saveData(data, file1,file2,file3)
    % 在此处编写后处理代码
    data1 = data{1};
    data2 = data{2};
    data3 = data{1};
    fprintf(file1,'%.10f ',  data1); 
    fprintf(file1,'\n'); 
    fprintf(file2,'%.10f ',  data2);
    fprintf(file2,'\n'); 
    fprintf(file3,'%.10f ',  data3);
    fprintf(file3,'\n'); 
end

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值