|
"James Tursa" <aclassyguywithaknotac@hotmail.com> writes:
> "Matt " <mjacobson.removethis@xorantech.com> wrote in
> message <g68b41$cu8$1@fred.mathworks.com>...
>>
>> I'm trying to understand if there is a difference in the
>> way copy-on-write is implemented for MEX functions as
>> compared to Mfiles.
>>
>> My understanding is as follows. As part of the copy-on-
>> write system, MATLAB will pass input data by reference to
>> an Mfile function if the function performs read-only
>> operations on that data. Otherwise, it will pass the data
>> by value.
>>
>
> No. MATLAB does not pre-parse the m-file to determine if an
> input variable is changed. MATLAB *always* passes the
> variables by reference. Once inside the m-file, if the input
> variable is changed, *then* MATLAB makes a copy. That is the
> copy-on-write behavior.
To expand on this a little, there is a C-level function in MATLAB that
"unshares" a variable. Internal functions in MATLAB that write to
variables (subsasgn, etc) call this function before writing to the
memory. Function parameters are exactly like assignments in the same
workspace. Nothing happens at function call time except a shared-data
assignment.
>> However, when it comes to MEX functions, the MATLAB interpreter
>> obviously cannot know the contents of the function and cannot
>> determine whether the operations it will perform are read-only or
>> otherwise. If MATLAB wanted to have all the same safety nets as for
>> Mfiles, it would have to always pre-duplicate the input data and send
>> that to the MEX function instead (effectively passing the data by
>> value).
>>
>> One reason for doing it this way would be to ensure that if
>> the MEX file crashes, the input data would remain unaltered
>> in the caller workspace. This will be true for Mfiles, and
>> the MATLAB software designers may have wanted it to be true
>> for MEX files as well.
>>
>
> There is no safety net for MEX files. There is no
> copy-on-write behavior for MEX files. The variables are
> passed by reference to the MEX file, same as an m-file. If
> you change an input variable in a MEX file, then the
> original is changed (as well as all other variables that
> share the same data memory). This can mess up the workspace
> of course, which is why you see warnings to never do this in
> the doc. However, it *is* safe to do if you *know* that the
> data memory is not shared with another variable. This can be
> tricky and is not recommended unless you really need to
> (e.g., very large variables that you don't want duplicated).
The MEX API clearly defines the input variables as "const". You can
defeat this, of course, but you shouldn't unless you're willing to
really dig into what happens at this level, and need that extra 5%
efficiency for some in-place computation.
-Peter
|