Starting and managing threads

Tejas notrealemail at gmail.com
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.

```d
import std.concurrency;
import core.thread;
import std.stdio:writeln,readf;
void main() {
   writeln("Please enter num of elements");
   int a;
   readf!"%d"(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
   }
	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)/+using cast so that TLS gets 
disabled)+/this.watchers) {
			spawn(&Watcher.run, watcher);
		}
	}
}

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


More information about the Digitalmars-d-learn mailing list