Shutting down thread with Socket blocking for connection
Vidar Wahlberg
canidae at exent.net
Sun Mar 4 13:46:40 PST 2012
Coming from a C++/Java world I find D's approach to concurrency slightly
difficult to grasp, perhaps someone could help me out a bit on this problem:
I'd like to have a method that spawns a new thread which sets up a
socket and listens for connections (in a blocking fashion). This part is
easy, the hard part is nicely shutting down the thread listening for
connections.
Here's some quick code (ignore the fact that even if "sock" was shared,
you would not be guaranteed that it was initialized correctly by the
time you call "shutdown()" and "close()"):
*************
import std.concurrency;
import std.socket;
/*shared*/ Socket sock;
void main() {
spawn(&listen);
/* do stuff */
sock.shutdown(SocketShutdown.BOTH);
sock.close();
}
void listen() {
sock = new TcpSocket();
sock.blocking = true;
sock.bind(new InternetAddress(8080));
sock.listen(10);
sock.accept(); // assume no connection was made, thus still
blocking
}
*************
If I make "sock" shared, then I'm not allowed to call any methods on
"sock" in "listen()" ("is not callable using argument types (...) shared").
I came across a post about a similar issue in this mail group from
Andrew Wiley (2011-02-15 23:59) which had some example code, but I could
not get that code to compile. Neither could I find an example in TDPL
that shows how to deal with threads that are blocked.
Basically, how would I go on about nicely stopping a thread that's
waiting for connections?
More information about the Digitalmars-d-learn
mailing list