d的同步类和共享

原创
2022/08/20 04:09
阅读数 74

原文
根据官方文档处理shared变量时,只允许原子操作它们.但是由于只能一个线程访问synchronized类,因此即使在shared环境中,允许访问其成员也是合理的,编译器至少应允许如下小代码:

synchronized class A{
  private:
    int a;
  public:
    this() {
      a = 1;
    }

    int getA() pure{
      return a;
    }
}

int main(){
  shared A c = new A();
  writeln(c.getA());
  return 0;
}

为什么官方文档中未添加该功能?
不同线程可访问shared数据,想向另一线程发送指针时,即使是synchronized类,指针数据也必须是shared,如下:

import std.stdio;
import std.concurrency;

synchronized class A{
    //略,两个函数都加了个纯...
}

void thread(A a){
  writeln(a.getA());
}

int main(){
  auto c = new A();
  spawn(&thread, c);
  return 0;
}

不编译,要编译:

import std.stdio;
import std.concurrency;

synchronized class A{
    //略,两个函数都加了个纯...
}

void thread(shared A a){
  writeln(a.getA());
}

int main(){
  auto c = new shared A();//共享.
  spawn(&thread, c);
  return 0;
}

必须加共享.

本文同步分享在 博客“fqbqrr”(CSDN)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
0 收藏
0
分享
返回顶部
顶部