原文 根据官方文档处理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;
}
必须加共享.









