How to work around the infamous dual-context when using delegates together with std.parallelism
Christian Köstlin
christian.koestlin at gmail.com
Thu May 27 14:13:08 UTC 2021
On 2021-05-27 15:00, sighoya wrote:
> On Thursday, 27 May 2021 at 12:58:28 UTC, Christian Köstlin wrote:
>
>> That looks nice, but unfortunately my data for servers and users in
>> the real world is not static but comes from a config file.
>
> Okay, but then parametrizing the static lambda with runtime parameters
> should work. The important fact is that the closure needs to be static.
Ah thanks, now I understand.
So what I came up with now is a combination of the things mentioned:
```D
import std;
string doSomething(string[] servers, string user) {
return user ~ servers[0];
}
struct UserWithServers {
string user;
string[] servers;
}
void main(string[] args) {
auto servers = args;
auto users = ["u1", "u2", "u3"];
auto usersWithServers = users.map!(user => UserWithServers(user,
servers)).array;
static fn = function(UserWithServers user) =>
user.servers.doSomething(user.user);
writeln(taskPool.amap!(fn)(usersWithServers));
}
```
Making also the example a little bit more "realistic" by using dynamic
data for servers.
I would like to use auto fn, but somehow saying that its a function is
not enough for dmd. From my understanding a function would never need a
context?!?
Thanks a lot!
Christian
P.S.: I still do not get how to post formatted snippets with thunderbird
to the newsgroup/forum :/
More information about the Digitalmars-d-learn
mailing list