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;
		}
	}
}
posted @   zjh6  阅读(17)  评论(0编辑  收藏  举报  
相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现
点击右上角即可分享
微信分享提示