Synchronize Class fields between different threads

bauss jj_1337 at live.dk
Fri Nov 10 15:01:30 UTC 2017


On Friday, 10 November 2017 at 14:36:03 UTC, DrCataclysm wrote:
> On Friday, 10 November 2017 at 14:27:41 UTC, bauss wrote:
>> On Friday, 10 November 2017 at 14:13:26 UTC, DrCataclysm wrote:
>>> On Friday, 10 November 2017 at 13:50:56 UTC, rikki cattermole 
>>> wrote:
>>>> Remember this bit: Everything on the heap, is not 
>>>> thread-local, it is global. This includes everything inside 
>>>> a class.
>>>>
>>>> When you synchronize (statement) it is locking and then 
>>>> unlocking a mutex. A class has a mutex, simple! It only 
>>>> prevent multiple threads modifying a single thing at 
>>>> specific times, thats all.
>>>
>>> this is my implementation of Accept
>>>
>>>
>>> private void Accept(){
>>>         // start accepting in a different thread
>>>         try{
>>>             _client = _server.accept();
>>>             
>>> emit(ClientConnected(_client.remoteAddress.toAddrString));
>>>             auto _acceptTask = task(&this.Accept);
>>>             _acceptTask.executeInNewThread();
>>>             Receive();
>>>         }
>>>         catch (SocketAcceptException e){
>>>             writeln("Error while accepting connection: " ~ 
>>> e.msg);
>>>         }
>>>     }
>>>
>>> Is _client on the Heap or the Stack? If it is on the Stack, 
>>> how would i get in on the Heap?
>>
>> _client is allocated in the heap.
>>
>> Socket accept(); returns the socket created from Socket 
>> accepting().
>>
>> Which is like below:
>>
>>  protected Socket accepting() pure nothrow
>>     {
>>         return new Socket;
>>     }
>
> thank you, i thought i was going mad.
>
> It is working now. The problem was that the debugger in eclipse 
> ddt seems to completely broken. If i run it directly from bash 
> it is working.
>
> One last question: is there a function in the std to wait for a 
> task to finish within a time limit?

Not an ideal solution, but should work: (I'm not aware of any 
build-in solutions using Phobos' tasks.

```
static const timeLimit = 1000; // Wait for the task up to 1000 
milliseconds

while (!task.done && timeLimit)
{
     import core.time : Thread, dur;

     Thread.sleep( dur!("msecs")(1) ); // Preventing the CPU to go 
nuts
     timeLimit--;
}

if (task.done)
{
     auto value = task.yieldForce();
}
```

Could make it a function though:

```
bool yieldTimeLimit(Task)(Task task)
{
     while (!task.done && timeLimit)
     {
         import core.time : Thread, dur;

         Thread.sleep( dur!("msecs")(1) );
         timeLimit--;
     }

     return task.done;
}

...

if (yieldTimeLimit(task))
{
     auto value = task.yieldForce();
}
```


More information about the Digitalmars-d-learn mailing list