On Tuesday, 28 December 2021 at 15:42:04 UTC, Tejas wrote:
On Tuesday, 28 December 2021 at 14:19:46 UTC, Bagomot wrote:
On Monday, 27 December 2021 at 10:59:07 UTC, Ali Çehreli wrote:
On 12/27/21 1:33 AM, Bagomot wrote:
> separate thread, without blocking the main one.
I think you can use std.concurrency there. I have a chapter
here:
http://ddili.org/ders/d.en/concurrency.html
Look for 'struct Exit' to see how the main thread signals
workers to stop running.
And some std.concurrency hints appear in my DConf Online 2020
presentation here:
https://dconf.org/2020/online/#ali1
Ali
I tried to run with std.concurrency via spawn, but this does
not work for me for the reason that in the program I run the
thread not from main, but from the object. It looks something
like this:
```d
import std.concurrency;
import std.thread;
void main() {
Test.getInstance.run;
}
class Test {
private {
__gshared Test instance;
Watcher[] watchers;
}
protected this() {
}
public static Test getInstance() {
if (!instance) {
synchronized (Test.classinfo) {
if (!instance)
instance = new Test;
}
}
return instance;
}
public void run() {
foreach (Watcher watcher; this.watchers) {
spawn(&watcher.run);
}
}
}
class Watcher {
public void run() {
while (true) {
// job
}
}
}
```
Error: template `std.concurrency.spawn` cannot deduce function
from argument types `!()(void delegate())`.
I would not want to do this from main because it breaks the
structure of my program. Is there a way to do it the way I
want?
Yes, you'll have to make the function that you want to run
static and all the arguments must be `shared` qualified, ie,
TLS not allowed
```d
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()];
//notice the shared // I used 2 values just to show some output
}
protected this() {
}
public static Test getInstance() {
if (!instance) {
synchronized (Test.classinfo) {
if (!instance)
instance = new Test;
}
}
return instance;
}
public void run() {
foreach (ref/+use ref to ensure no copies are made. I don't
tknow the right thing to do here, the errors went away when I
used ref so...+/ watcher; this.watchers) {
spawn(&Watcher.run, watcher);
}
}
}
class Watcher {
static public void run(shared Watcher watcher/+sending as
argument since function can't have an invisible this parameter
anymore+/) {//now this is static
while (true) {
// job
writeln("It works now :D");
break; //wrote this so that you can copy-paste to
run.dlang.io
}
}
}
```
I can't do it according to your example, my Watcher list fills up
at runtime.