Avoid memory copy in thread-based environment (parfeval)

조회 수: 5 (최근 30일)
Thomas Witkowski
Thomas Witkowski 2023년 11월 8일
편집: Thomas Witkowski 2023년 11월 15일
Is it possible to avoid memory copy of the input data to each individual worker when using a thread based environment (thus with shared memory)? Here a very simple example on what I'm intended to do:
function compMat()
m = rand(1000000000, 1);
c1 = f1(m);
c2 = f2(m);
fprintf("%f %f\n", c1, c2);
p1 = parfeval(backgroundPool, @f1, 1, m);
p2 = parfeval(backgroundPool, @f2, 1, m);
c1 = fetchOutputs(p1);
c2 = fetchOutputs(p2);
fprintf("%f %f\n", c1, c2);
end
function x = f1(m)
x = mean(sin(m));
end
function x = f2(m)
x = mean(cos(m));
end
The input data is quite large, but the two operations f1 and f2 on this data don't need a copy of the data. Is it possible to reimplement the above example such that all the time there is only one instance of the input vector in memory and the operations f1 and f2 run in parallel on it?

채택된 답변

Edric Ellis
Edric Ellis 2023년 11월 9일
In this case, thread-based workers already avoid copying the large array m to the workers. See this section in the doc. Note that when you call sin(m) that will create a new temporary array of the same size as m for the output.
Perhaps somewhat counter-intuitively for MATLAB, you might be better off using a for loop (rather than vectorised operations as you have in your example code) to operate on the large array m to avoid making same-sized temporary arrays during the computation.
  댓글 수: 1
Thomas Witkowski
Thomas Witkowski 2023년 11월 13일
편집: Thomas Witkowski 2023년 11월 15일
Thanks, I've completly overseen that sin(m) / cos(m) creates a temporary array. I've check the memory behavior with a for loop working on m. The memory consumption is than as expected in multi threaded environment.

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

추가 답변 (0개)

카테고리

Help CenterFile Exchange에서 Startup and Shutdown에 대해 자세히 알아보기

제품


릴리스

R2023a

Community Treasure Hunt

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

Start Hunting!

Translated by