0
点赞
收藏
分享

微信扫一扫

d的同步类和共享


​​原文​​​ 根据官方文档处理​​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;
}

必须加​​共享​​.


举报

相关推荐

0 条评论