void pollresponse(const RonSwansons__pollresp_impl * pollresp) { int client = pollresp->clientid; if(pollresp->reqfork1 == 1) { printf("pollresponse: received initial fork request from Ron %i.\n",client); int fork = allocfork(0,FORKS-1); if(fork < 0) { printf("pollresponse: could not find initial fork for Ron %i.\n",client); RonSwansons__fork_impl forkmsg; forkmsg.forkid = -1; givefork(client,&forkmsg); return; } RonSwansons__fork_impl forkmsg; forkmsg.forkid = fork; givefork(client,&forkmsg); } else if (pollresp->reqfork2 >= 0 && pollresp->reqfork2 < FORKS) { printf("pollresponse: received second fork request from Ron %i for fork id greater than %i.\n",client,pollresp->reqfork2); int fork = allocfork(pollresp->reqfork2,FORKS); if(fork < 0) { printf("pollresponse: could not find second fork for Ron %i.\n",client); RonSwansons__fork_impl forkmsg; forkmsg.forkid = -1; givefork(client,&forkmsg); return; } RonSwansons__fork_impl forkmsg; forkmsg.forkid = fork; givefork(client, &forkmsg); } else { printf("Bad poll response received on pollresponseport%i.\n",client); } }
void poll(const RonSwansons__fork_impl * fork_data) { printf("Ron %i: I am taking action.\n",ID); if(fork1<0) { // Ron has no forks. printf("Ron %i: I am requesting an initial fork.\n",ID); RonSwansons__pollresp_impl pollresp; pollresp.clientid = ID; pollresp.reqfork1 = 1; pollresp.reqfork2 = -1; waiting++; pollresponse(&pollresp); } else if (fork2<0) { // Ron has one fork. printf("Ron %i: I am requesting a second fork with an id greater than %i.\n",ID,fork1); RonSwansons__pollresp_impl pollresp; pollresp.clientid = ID; pollresp.reqfork1 = 0; pollresp.reqfork2 = fork1; waiting++; pollresponse(&pollresp); } else if (eatpolls>0) { // Ron is eating printf("Ron %i: Nom nom nom with forks %i and %i.\n",ID,fork1,fork2); eatpolls--; } else { // Return forks. printf("Ron %i: I am returning forks %i and %i.\n",ID,fork1,fork2); RonSwansons__fork_impl fork1msg; RonSwansons__fork_impl fork2msg; fork1msg.clientid = ID; fork1msg.forkid = fork1; fork1 = -1; fork2msg.clientid = ID; fork2msg.forkid = fork2; fork2 = -1; bool f1 = givefork(&fork1msg); if(!f1) { printf("Ron %i: failed to return fork %i.\n",ID,fork1); } bool f2 = givefork(&fork2msg); if(!f2) { printf("Ron %i: failed to return fork %i.\n",ID,fork2); } } }