小编Flo*_*sch的帖子

使用全局变量在Dart中的函数之间共享对象是否安全?

我看到“ Dart是一种单线程编程语言”,所以我认为使用全局变量在函数之间传递数据是安全的:

var g = 1;

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

def hello() {
    g = 2;
}

def world() {
    print(g);
}
Run Code Online (Sandbox Code Playgroud)

我还看到“ Dart提供隔离”并且可以在多核上运行。这意味着如果不同的隔离株访问相同的全局变量可能会很危险,对吗?

安全吗?如果不是,是否有任何方法可以在函数之间共享对象而不将它们作为参数传递?


更新:

根据“ Florian Loitsch”的回答,我刚刚编写了一个针对带有隔离的全局变量的测试:

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();
}
Run Code Online (Sandbox Code Playgroud)

您会看到一个隔离将全局变量g设置为新值,而另一个隔离将打印的值g

它打印的控制台:

I'm 2
I received: …
Run Code Online (Sandbox Code Playgroud)

global-variables dart dart-isolates

6
推荐指数
1
解决办法
2568
查看次数

Dart 编辑器按位异或显示为未知

当前版本的 Dart Editor 将按位异或运算符显示为not defined for class bool

我没有看到它被定义num.dart

前任:

bool x = a ^ b;
Run Code Online (Sandbox Code Playgroud)

编辑器将“插入符”显示为未定义。

更新:Dart 的 api 规范仅允许对整数进行按位异或。我修复了我的代码以正确使用bools。

dart dart-editor

5
推荐指数
1
解决办法
6212
查看次数

哪些未定义的行为允许这种优化?

我正在开发一个虚拟机,它使用典型的 Smi(小整数)编码,其中整数表示为标记指针。更准确地说,指针被标记,而整数只是被移动。

这与 V8 和 Dart 采取的方法相同: https: //github.com/v8/v8/blob/main/src/objects/smi.h#L17

在我们的实现中,我们有以下 Smi 代码:

// In smi.h

#include <stdint.h>

class Object {
 public:
  bool is_smi() const { return (reinterpret_cast<uintptr_t>(this) & 0x1) == 0; }
};

class Smi : public Object {
 public:
  intptr_t value() const { return reinterpret_cast<intptr_t>(this) >> 1; }
  static Smi* from(intptr_t value) { return reinterpret_cast<Smi*>(value << 1); }
  static Smi* cast(Object* obj) { return static_cast<Smi*>(obj); }
};
Run Code Online (Sandbox Code Playgroud)

通过此设置,gcc 12.1.0 优化了以下函数,因此当Smi 值为 0-O3时,永远不会采用“if” 。o

// bad_optim.cc
#include …
Run Code Online (Sandbox Code Playgroud)

c++ undefined-behavior

3
推荐指数
1
解决办法
110
查看次数

Dart - 如何提供gzip编码的html页面

我正在尝试gzip .html文件然后管道它HttpResponse.

import 'dart:io';

void main() {
  File f = new File('some_template.html');
  HttpServer.bind('localhost', 8080)
    .then((HttpServer server) {
      server.listen((HttpRequest request) {
        HttpResponse response = request.response;
        f.openRead()
          .transform(GZIP.encoder)
          .pipe(response);
      });
    });
}
Run Code Online (Sandbox Code Playgroud)

没有错误,但浏览器不是提供html页面,而是下载压缩的html页面.小心给我一个提示?

dart

2
推荐指数
1
解决办法
834
查看次数