Is it safe to use global variable to share objects between functions in Dart?
Asked Answered
S

1

8

I see that "Dart is a single-threaded programming language", so I think is it safe to use global variable to pass data between functions:

var g = 1;

main() {
   hello();
   world();
}

def hello() {
    g = 2;
}

def world() {
    print(g);
}

I also see that "Dart provides isolates" and which can run on multi-cores. That means it may be dangerous if different isolates visit the same global variable, right?

Is it safe? And if not, is there any way to share objects between functions without passing them as parameters?


Update:

Per "Florian Loitsch"'s answer, I just wrote a testing for the global variable with isolates:

import 'dart:isolate';

var g = 1;

echo() {
  port.receive((msg, reply) {
    reply.send('I received: $g');
  });
}

main() {
  var sendPort = spawnFunction(echo);

  void test() {
    g = 2;
    sendPort.call('Hello from main').then((reply) {
      print("I'm $g");
      print(reply);
      test();
    });
  }
  test();
}

You can see one isolate will set the global variable g to a new value, and another isolate will print the value of g.

The console it prints:

I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1
I'm 2
I received: 1

It's clear that they don't share memory, and global variable is safe.

Sensualist answered 23/6, 2013 at 15:20 Comment(0)
G
8

Dart is single-threaded within one thread. It is hence safe (though bad style) to pass data in global variables.

Isolates have their separate heaps (memory) and don't interfere with each other. Global variables stay safe.

I don't think there is a way to pass variables between functions except for static variables and parameters.

Genitalia answered 23/6, 2013 at 15:58 Comment(3)
So it's safe even if I use isolates? That's great, let me write some code to testSensualist
I just write a demo to prove it, and updated my question. Thank you again:)Sensualist
You do have to be aware that async code may cause some degree of shared access, but it's much less than you'd have with threads, and more predictable.Brackett

© 2022 - 2024 — McMap. All rights reserved.