help for example with Condition

Andrea Fontana nospam at example.com
Thu Sep 11 09:44:06 UTC 2025


On Thursday, 11 September 2025 at 09:29:29 UTC, Mikhail wrote:
> I wrote simple example to learn how the work Conditions.
> But program closed with signal, what's wrong?
>
> import std.stdio;
> import core.thread;
> import core.sync.condition;
> import core.sync.mutex;
>
>
> Condition cond;
> Mutex mutex;
>
> void threadFunction()
> {
>     writeln("This is running in a separate thread.");
>     Duration d = dur!"msecs"(100);
>     writeln(d);
>     cond.wait(d);
> }
>
> void main() {
>     mutex = new Mutex();
>     cond = new Condition(mutex);
>
>     auto t = new Thread(&threadFunction);
>     t.start();
>
>     t.join();
>     writeln("Main thread finished.");
> }

1) cond & mutex vars are thread local vars. If you init them from 
the main function, they are not shared with thread. You need to 
use __gshared o shared.

2) I think you have to do mutex.lock(); and scope(exit) 
mutex.unlock(); before calling cond.wait(d) or use 
syncronized(mutex) {  } inside thread for example:


Here mutex and cond are visible from inside the thread. All local 
vars are visible.

```
void main() {
     auto mutex = new Mutex();
     auto cond = new Condition(mutex);

     auto t = new Thread({

         writeln("This is running in a separate thread.");
         Duration d = dur!"msecs"(100);
         writeln(d);

         mutex.lock();
         scope(exit) mutex.unlock();
         cond.wait(d);

     });

     t.start();

     t.join();
     writeln("Main thread finished.");
}
```

```
void main() {
     auto mutex = new Mutex();
     auto cond = new Condition(mutex);

     auto t = new Thread({

         writeln("This is running in a separate thread.");
         Duration d = dur!"msecs"(100);
         writeln(d);

         synchronized(mutex)
         {
             cond.wait(d);
         }

     });

     t.start();

     t.join();
     writeln("Main thread finished.");
}
```

Andrea


More information about the Digitalmars-d-learn mailing list