Member variables in method are null when called as delegate from thread

Arafel er.krali at gmail.com
Wed Jan 13 08:28:06 UTC 2021


On 13/1/21 3:15, Tim wrote:
> 
> Fantastic response, thank you! I did some more digging and properly 
> narrowed down where the issue is and created a test script that 
> demonstrates the problem. Let me know what you think and if it could 
> still be a similar problem to what you have stated above. I'll still 
> read that info you sent to sharpen up on these concepts.
> 
> Basically, the program calls a function which modifies a document in the 
> database. If it is called form it's own class' constructor, it works 
> fine. If it is called by a thread, it never returns. I don't think that 
> a member variable is going null or anything. But a strange problem that 
> I can't seem to debug. The output is at the bottom.
> 
> ----------------------------------------------------------------
> 
> import vibe.db.mongo.mongo;
> import core.thread;
> import std.stdio;
> 
> void main(){
>      auto callable = new Callable();
> 
>      while(true){}
> }
> 
> class Caller : Thread{
>      void delegate() mFunc;
> 
>      this(void delegate() func){
>          mFunc = func;
>          super(&loop);
>          start();
>      }
> 
>      void loop(){
>          while(true){
>              mFunc();
>          }
>      }
> }
> 
> class Callable{
>      MongoClient db;
>      Caller caller;
> 
>      this(){
>          db = connectMongoDB("127.0.0.1");
>          foo();
>          caller = new Caller(&foo);
>      }
> 
>      ~this(){
>      db.cleanupConnections();
>      }
> 
>      void foo(){
>          writeln("Started");
>          auto result = db.getCollection("test.collection").findAndModify([
>          "state": "running"],
>          ["$set": ["state": "stopped"]
>      ]);
>          writeln(result);
>          writeln("Finished");
>      }
> }
> 
> ----------------------------------------------------------------
> 
> Output:
>      Started
> {"_id":"5ff6705e21e91678c737533f","state":"running","knowledge":true}
>      Finished
>      Started

Something that you could try for debugging is to add a try / catch block 
around your call to `db.getCollection` (and printing out the exception 
details). IIRC, if a thread throws, it will just end without printing 
anything until the thread is joined, when the exception will be rethrown 
[1].

The program hanging would be then the main thread waiting. This kind of 
problem has already bitten me more than once...

[1]: https://dlang.org/library/core/thread/osthread/thread.join.html


More information about the Digitalmars-d-learn mailing list