It seems [=] functionality C++ does not exist in D.
By using a helper function I made that example work.
import std.stdio;
auto localFoo(int x) {
return (){ return x;};
}
void main() {
int x = 10;
auto lambda = (int capturedX = x) {
writeln("Captured reference : ", capturedX);
};
auto localFoo = localFoo(x);
x = 20;
writeln(localFoo());// Outputs: Captured value: 10 --> That is what I need
lambda(); // Outputs: 20
}
But when I trying the same technique on std.Thread it does not work. Always reference is being captured.
void InitCurrencies()
{
auto captureFuction(int index)
{
return (){
auto localIndex = index;
string[] currentChunk = ChunkedExchangePairNames(localIndex);
writeln("Thread index: ", localIndex, " pairs:
", currentChunk.join(";"));
foreach (exchangeName; currentChunk)
Connect(exchangeName, WebSocketType.All);
WebSocket.eventLoop(localLoopExited);
};
}
for(int i = 0; i < m_ThreadCount; i++)
{
auto work = captureFuction(i);
auto worker = new Thread({
work();
});
m_workerList ~= worker;
}
foreach(worker; m_workerList)
{
worker.start();
}
}
writeln("Thread index: ", localIndex, " pairs: ", currentChunk.join(";"))
Always prints the last value of my for loop.
Is there a way to capture the value on anonymous function which is being passed t std.Thread