|
-
August 25th, 2010, 02:55 AM
#1
Pass-by-value vs pass-by-reference
From a multithreaded and multi-processor/core perspective, what would be safer, pass-by-value or pass-by-reference?
I know there's no hard and fast rules, but what would you consider as a general guideline?
To me it feels that pass-by-reference is more risky in a multithreaded environment. Another thread can modify an object while a function is busy operating on it. Using pass-by-value decreases the chance of a mess happening. The downside of course is the overhead associated with passing large objects by value.
Last edited by links; August 25th, 2010 at 02:58 AM.
-
August 25th, 2010, 08:15 AM
#2
Re: Pass-by-value vs pass-by-reference
The real answer is, this isn't a sufficient question. You can follow guidelines like "prefer local variables to globals" and "don't use local statics" to make multithreading easier, but at the end of the day, you need to know for certain precisely where and when an object might be modified or read by more than one thread. Guessing isn't good enough.
However, one of those good rules of thumb you can follow is that passing by const reference is almost always as safe as passing by value, in terms of behavioral guarantees.
-
September 3rd, 2010, 06:39 PM
#3
Re: Pass-by-value vs pass-by-reference
Passing by const reference provides a behavioral guarantee only on the function to which the reference is passed. It does not provide any guarantees on the function doing the passing. If these functions are in different threads, it thus might happen that the passed-to function finds that the underlying value is changed out from underneath it.
It might be better to prefer pass by value, since then each function has its own local copy of the value, even though those values can easily become desynchronized.
PS: Sorry for the delayed post
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|