原文
根据官方文档处理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源创计划”,欢迎正在阅读的你也加入,一起分享。