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;
}
}
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列01:轻松3步本地部署deepseek,普通电脑可用
· 25岁的心里话
· 按钮权限的设计及实现