Explain implicit copying of variables on 'Isolates' page #5843
Labels
a.language
Relates to the Dart language tour
e2-days
Can complete in < 5 days of normal, not dedicated, work
from.page-issue
Reported in a reader-filed concern
st.triage.ltw
Indicates Lead Tech Writer has triaged
Page URL
https://dart.dev/language/isolates
Page source
https://github.com/dart-lang/site-www/tree/main/src/content/language/isolates.md
Describe the problem
The current section titled "Sending closures with isolates" does not explain that variables captured by the closure are implicitly copied into the new isolate.
See the following example:
Note that modifying
i
in the new isolate does not affect the value ofi
in the main isolate, becausei
was implicitly copied into the new isolate.One issue that people sometimes run into is that when refencing a class property in a closure sent to an isolate, the rest of the class instance gets copied as well. This can especially be an issue if the class contains an object of a type that is not allowed to be sent to an isolate (see https://api.dart.dev/stable/3.4.0/dart-isolate/SendPort/send.html).
See the following example:
The above code fails with the following exception:
A
ReceivePort
is one of the types of objects restricted from being sent to another isolate. Even though theport
variable was not explicitly referenced, it was still implicitly copied over due toi
being referenced. I believe this happens becauseprint(i);
is shorthand forprint(this.i);
in the above example.Expected fix
Add some explanation about implicit copying of variables, and potential issues.
Additional context
No response
I would like to fix this problem.
The text was updated successfully, but these errors were encountered: