Starting and managing threads

Bagomot bagomot at gmail.com
Tue Dec 28 14:19:46 UTC 2021


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?


More information about the Digitalmars-d-learn mailing list