Worker is not finished while sending message to intermediate worker
xtreak via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Mon Feb 9 08:00:35 PST 2015
I am using "programming in D" to learn about D language. I wrote
a simple program that spawns a worker and sends it a number to
receive its square as a string. The worker 1 gets the number
squares it and sends to worker 2 (a different function) to get
casted as string which is returned to the worker 1 and thus it
returns it to the main function call. I can write the whole thing
in a single thread. I wrote it to understand about workers
better. I used receive to get the worker 1 act as per the input.
The program is as follows
import std.stdio;
import std.concurrency;
import std.conv;
import core.thread;
void main() {
foreach (int num; 1..100) {
auto square_tid = spawn(&square);
square_tid.send(num);
auto square = receiveOnly!string();
writeln(square);
}
}
void square() {
static i = 0;
receive (
(int num) {
auto square = num * num;
writeln("sqaure : Comes in with " , num , " for " , ++i
, " time");
auto stringWorker = spawn(&stringConverter);
stringWorker.send(thisTid, square, ownerTid);
},
(Tid tid, string str) {
writeln("comes in string");
send(tid, "hello");
});
}
void stringConverter() {
static i = 0;
auto params = receiveOnly!(Tid, int, Tid)();
auto stringified = to!string(params[1]); // Stringify the square
writeln("string : Comes in with " , params[1], " for " , ++i ,
" time");
params[0].send(params[2], stringified); // params[0] - square
function tid, // params[2] - main function tid
}
I got the answer from stackoverflow @
https://stackoverflow.com/questions/28128383/worker-is-not-finished-while-sending-message-to-intermediate-worker.
But the person who answered my question asked me to post back to
dlang learn to learn more about it. As I spawn the function and a
send a message to stringConverter as it sends a message to the
square function why do I need to embed another receive call
inside the int case as indicated in the answer. How can I avoid
embedding the receive call and why does the person in the second
answer used while(1) to receive the message.
More information about the Digitalmars-d-learn
mailing list