d中运行线程.
必须设定函数为静,所有参数为共享.不允许tls.
import std.concurrency;
import core.thread;
import std.stdio:writeln;
void main() {
Test.getInstance.run;
}
class Test {
private {
__gshared Test instance;
shared Watcher[] watchers = [new Watcher(), new Watcher()]; //注意共享.用2个来显示.
}
protected this() {
}
public static Test getInstance() {
if (!instance) {
synchronized (Test.classinfo) {
if (!instance)
instance = new Test;
}
}
return instance;
}
public void run() {
foreach (ref watcher; this.watchers) {
spawn(&Watcher.run, watcher);
}//用引用确保不复制.没有它报错...
}
}
class Watcher {
static public void run(shared Watcher watcher) {//静态函数了.
while (true) {// job
writeln("现在工作:D");
break; //可粘贴.
}
}//按参数传递,因为函数不能有`不可见本(静)`.
}
我观察者列表填满了.不能上面这样.
import std.concurrency;
import core.thread;
import std.stdio:writeln,readf;
void main() {
writeln("请输入元素数");
int a;
readf!"%d"(a);
foreach(number; 0..a){
Test.getInstance.watchers ~= new Watcher();
}//读写共享变量时,要用`core.atomic`中操作,因而这里不声明数组为`共享`.
Test.getInstance.run;
}
class Test {
private {
__gshared Test instance;
/+shared+/ Watcher[] watchers;
}//不用共享.
protected this() {
}
public static Test getInstance() {
if (!instance) {
synchronized (Test.classinfo) {
if (!instance)
instance = new Test;
}
}
return instance;
}
public void run() {
foreach (ref watcher; cast(shared)this.watchers) {
spawn(&Watcher.run, watcher);
}//用`cast`来禁止`tls`.
}
}
class Watcher {
static public void run(shared Watcher watcher) {
while (true) {// job
writeln("工作了:D");
break;
}
}
}
浙公网安备 33010602011771号