I have a multicast receive daemon that is running as a NSThread. While it’s waiting to receive, I’d like to be able to cancel it without waiting for another packet which may not come. Since it’s just waiting, I can’t execute other code to check isCancelled. How can I do this?
Here’s the code that is receiving.. It sits and waits on the first line until a packet comes in.
/* block waiting to receive a packet */
if ((recv_len = recvfrom(sock, recv_str, MAX_LEN, 0,
(struct sockaddr*)&from_addr, &from_len)) < 0) {
[delegate multicastDaemonDidFinish:self withError:@"recvfrom() failed"];
exit(1);
}
receivedString = [NSString stringWithFormat:@"%s", recv_str];
[delegate multicastDaemonDidReceiveData:self receivedString:receivedString];
In the parent, who is also the delegate, this Thread is called by:
[daemonThread initWithTarget:multicastDaemon selector:@selector(doWorkWithDelegate:) object:self];
[daemonThread start];
I can issue a [daemonThread cancel], but daemonThread will never check isCancelled while he’s waiting. How can I do this?
You could loop on a select call with a timeout. If the select returns 0, then it timed out so you have the opportunity to check on the cancel flag, and either exit the thread or perform the select again. If there is something to receive then process it with recevfrom and exit out of the loop.