The Art of R Programming

(WallPaper) #1
and in myRdsmpackage (both available on CRAN, R’s code repository; see
this book’s appendix for details), as follows:

•Insnow, the server sends out work tasks to the clients. The clients per-
form their tasks and send the results back to the server, which assem-
bles them into the final result. Communication is done withserialize()
andunserialize(), and the server usessocketSelect()to determine which
client results are ready.


  • Rdsmimplements a virtual shared-memory paradigm, and the server is
    used to store the shared variables. The clients contact the server when-
    ever they need to read or write a shared variable. To optimize speed,
    communication between server and clients is done withreadBin()and
    writebin(), instead ofserialize()andunserialize().


Let’s look at some of the socket-related details ofRdsm. First, here is the
server code in which connections with the clients are set up, storing them in
a listcons(there arenconclients):

1 # set up socket connections with clients
2 #
3 cons <<- vector(mode="list",length=ncon) # list of connections
4 # prevent connection from dying during debug or long compute spell
5 options("timeout"=10000)
6 for (i in 1:ncon) {
7 cons[[i]] <<-
8 socketConnection(port=port,server=TRUE,blocking=TRUE,open="a+b")
9 # wait to hear from client i
10 checkin <- unserialize(cons[[i]])
11 }
12 # send ACKs
13 for (i in 1:ncon) {
14 # send the client its ID number, and the group size
15 serialize(c(i,ncon),cons[[i]])
16 }


Since the client messages and server acknowledgments are short mes-
sages,serialize()andunserialize()are good enough for the purpose here.
The first part of the main loop of the server finds a ready client and
reads from it.

1 repeat {
2 # any clients still there?
3 if (remainingclients == 0) break
4 # wait for service request, then read it
5 # find all the pending client requests
6 rdy <- which(socketSelect(cons))
7 # choose one
8 j <- sample(1:length(rdy),1)

Input/Output 249
Free download pdf