Starting and managing threads

Bagomot bagomot at gmail.com
Sat Jan 15 08:34:15 UTC 2022


On Wednesday, 12 January 2022 at 08:50:09 UTC, Bagomot wrote:
> Good day! I keep giving rise to problems.
> Above, Tejas helped me a lot, but still doesn't work.
> I gave up using the fswatch library, thinking that the problem 
> was in it.
> Now trying to do it using libasync.
>
> Here is the code that runs on the main thread, it blocks 
> further actions on that thread.
> ```d
> #!/usr/bin/env dub
> /+ dub.sdl:
> 	dependency "libasync" version="~>0.8.6"
> +/
>
> import std.stdio;
> import std.file;
> import std.algorithm;
> import core.thread;
> import std.concurrency;
>
> import libasync;
> import libasync.watcher;
> import libasync.threads;
>
> void main() {
>
> 	string testDir = "temp";
> 	if (!testDir.exists)
> 		mkdir(testDir);
>
> 	Guard guard = Guard.getInstance;
> 	guard.addWatchedDir(testDir, false);
> 	guard.run;
>
> 	writeln("Some kind of action...");
> }
>
> class Guard {
> 	private {
> 		__gshared Guard instance;
> 		static EventLoop eventLoop;
> 		WatchedDir[] watchedDirs;
> 	}
>
> 	protected this() {
> 		this.eventLoop = getThreadEventLoop();
> 	}
>
> 	shared static ~this() {
> 		destroyAsyncThreads();
> 	}
>
> 	public static Guard getInstance() {
> 		if (!instance) {
> 			synchronized (Guard.classinfo) {
> 				if (!instance)
> 					instance = new Guard;
> 			}
> 		}
>
> 		return instance;
> 	}
>
> 	public void run() {
> 		while (eventLoop.loop()) {
> 			continue;
> 		}
> 	}
>
> 	public void addWatchedDir(string dir, bool recursive = true, 
> string[] exclude = [
> 		]) {
> 		if (this.watchedDirs.canFind!(a => a.dir == dir))
> 			return;
>
> 		this.watchedDirs ~= new WatchedDir(dir, recursive, exclude);
> 	}
>
> 	class WatchedDir {
> 		private {
> 			string dir;
> 			bool recursive;
> 			string[] exclude;
> 			AsyncDirectoryWatcher watcher;
> 			DWChangeInfo[8] changeBuf;
> 		}
>
> 		this(string dir, bool recursive, string[] exclude) {
> 			this.dir = dir;
> 			this.recursive = recursive;
> 			this.exclude = exclude;
> 			this.watcher = new AsyncDirectoryWatcher(eventLoop);
>
> 			this.watcher.run({
> 				DWChangeInfo[] changes = changeBuf[];
> 				uint cnt;
>
> 				do {
> 					cnt = this.watcher.readChanges(changes);
> 					foreach (i; 0 .. cnt) {
> 						writeln("Main Callback got directory event: ", 
> changes[i]);
> 					}
> 				}
> 				while (cnt > 0);
> 			});
> 			this.watcher.watchDir(this.dir, DWFileEvent.ALL, 
> this.recursive);
> 		}
> 	}
> }
> ```
> If I change the run method of the Guard class so that it starts 
> a new thread, the program just does nothing:
> ```d
> public void run() {
> 	spawn((shared EventLoop eventLoop) {
> 		while ((cast() eventLoop).loop()) {
> 			continue;
> 		}
> 	}, cast(shared) this.eventLoop);
> }
> ```
> Why? What am I doing wrong?

Actual!


More information about the Digitalmars-d-learn mailing list