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

Steven Schveighoffer schveiguy at gmail.com
Mon Jan 11 13:42:09 UTC 2021


On 1/11/21 3:21 AM, Arafel wrote:
> On 11/1/21 1:43, Tim wrote:
>> Hi there,
>>
>> I have something like this:
>>
>> class Foo{
>>      MongoClient db;
>>
>>      this(){
>>          db = connectMongoDB("127.0.0.1");
>>          void delegate()[string] commands = ["start": &this.start];
>>      MessageService messenger = new MessageService(8081, commands);
>>      }
>>
>>      void start(){
>>          // Do something with db
>>      }
>>
>> MessageService is a thread that deals with socket communication. When 
>> a command comes in, it calls the appropriate delegate given to it by 
>> commands. When MessageService calls the delegate for start, db is 
>> null. If I call start() in the Foo constructor it works just fine. Am 
>> I missing something here? Do delegates get called outside of their 
>> class context? I know I could just pass the db into start but I want 
>> to work out exactly why this is happening
>>
>> Thanks in advance
> 
> Hi,
> 
> Member variables are thread-local by default. At the very least you'll 
> need to make `db` `shared` and manually verify that it's safe to use 
> them before casting it away. So your code could end up a bit like this:

That isn't exactly true. Member variables are members of the object. If 
the object is shared, the member variables are shared. If the object is 
local the variables are local.

Thread local really only applies to *static* variables, such as globals 
or members declared static. If that were the case, yes, the other thread 
would not see the object.

I did not respond to the OP because I also don't know why it wouldn't 
work. But I also don't know what all the code is doing.

-Steve


More information about the Digitalmars-d-learn mailing list