Starting and managing threads

Tejas notrealemail at
Tue Dec 28 17:11:36 UTC 2021

On Tuesday, 28 December 2021 at 16:29:05 UTC, Bagomot wrote:

> I can't do it according to your example, my Watcher list fills 
> up at runtime.

Yes, it's possible to do it at runtime as well(it already _was_ 
happening at runtime), although I'll be using a `cast` for 
convenience now.

import std.concurrency;
import core.thread;
import std.stdio:writeln,readf;
void main() {
   writeln("Please enter num of elements");
   int a;
   foreach(number; 0..a){
     Test.getInstance.watchers ~= new Watcher();//will have to use 
operations from core.atomic if you want to read/write shared 
variables, that's why I didn't declare the array as shared

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)/+using cast so that TLS gets 
disabled)+/this.watchers) {
			spawn(&, watcher);

class Watcher {
	static public void run(shared Watcher watcher) {
		while (true) {
			// job
       writeln("It works now :D");

More information about the Digitalmars-d-learn mailing list