Capture context surrounding delegate

Tim tim.dlang at t-online.de
Sat May 10 11:35:41 UTC 2025


On Saturday, 10 May 2025 at 04:52:15 UTC, Python wrote:
> Too much code below, but I cannot reduce it more. The issue is 
> in the main function, I want to pass a delegate to a thread 
> with a captured value from the surrounding context. At least 
> this was my expectation, the delegate should capture any stack 
> value.
>
> Am I doing something wrong?

This is a known issue. See e.g. 
https://github.com/dlang/dmd/issues/18108

A workaround is to put the loop body in an additional function, 
which is directly called:

```d
      for (int i = 0; i < 100; ++i)
      {
          (){
              auto captured = i;
              ThreadPool.enqueue(() {
                  writefln("Item: %d on thread %d, running %d 
threads",
     captured, Thread.getThis.id, ThreadPool.threads);
              });
          }();
      }
```


More information about the Digitalmars-d-learn mailing list