Handling Mutually Exclusive variable in background processes

조회 수: 43 (최근 30일)
ARIVARASAN
ARIVARASAN 2024년 11월 7일 6:29
댓글: ARIVARASAN 2024년 11월 11일 7:35
I have two functions where I access a shared variable.
% Create a shared variable using parallel.pool.Constant
sharedVar = parallel.pool.Constant(@() 0); % Initialize shared variable to 0
% Function 1: Increment the shared variable
function incrementSharedVar(sharedVar)
sharedVar.Value = sharedVar.Value + 1; % Increment shared variable
end
% Function 2: Decrement the shared variable
function decrementSharedVar(sharedVar)
sharedVar.Value = sharedVar.Value - 1; % Decrement shared variable
end
I run these functions in background.
% Run the increment and decrement functions as background tasks
f1 = parfeval(@incrementSharedVar, 0,sharedVar);
f2 = parfeval(@decrementSharedVar, 0,sharedVar);
% Wait for both tasks to complete
wait([f1, f2]);
How to ensure the mutual exclusion among this shared variable so that one function waits while the other function updates the value?

채택된 답변

Sumukh
Sumukh 2024년 11월 7일 11:03
To run the functions ”f1” and “f2” as background tasks, the term "backgroundPool" must be passed as the first argument to "parfeval". You can refer to the following documentation to know more about this syntax:
The provided code does not change the value of the Constant object "sharedVar" because the value of the Constant object is read-only and cannot be changed once initialized. More details about the Constant object can be found in the following documentation:
A possible method to provide gaps between execution of the “parfeval” functions “f1” and “f2“ is to use DataQueue object. The DataQueue object can be used to create a queue of function calls by calling “f1” and “f2” one after the other using the “afterEach” command. Kindly refer to the following documentation to know more about the DataQueue object and its function "afterEach":
I hope this answers your query.
  댓글 수: 1
ARIVARASAN
ARIVARASAN 2024년 11월 11일 7:35
Hey!! Thanks for your reply. I read more about this including the links you provided. I need to execute these functions parallelly in the background where they parallelly edit a variable in a mutually exclusive manner. "parfeval" seems to achieve this, but I can't seem to get my head around how to share a mutually exclusive variable among the baclground processes. This is a bit tricky. Any ideas?

댓글을 달려면 로그인하십시오.

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Background Processing에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by