Section 7.7. Event Handling with Independent Threads


7.7. Event Handling with Independent Threads

DNS-SD also accommodates programmers who prefer to use multiple threads rather than a single thread and an event loop. Because the DNSServiceProcessResult( ) blocks if no data is available, you can simply create a thread and have it spin calling DNSServiceProcessResult( ). When no data is available, the thread will sleep. When data arrives, the thread will wake up, handle it, and then go back to sleep again. Example 7-11 shows how to set up event handling using independent threads .

Example 7-11. Event handling with independent threads
 void ThreadProc(DNSServiceRef ref)     {     while (DNSServiceProcessResult(ref) == kDNSServiceErr_NoError)         continue;     } 

This has the advantage that your callback routines will get executed "by magic," without you having to take any special action aside from creating the thread and starting it running in the first place. Of course, magic comes at a price. When callback routines get executed by magic, you no longer have control over exactly when they will run and what else might be happening at the same time. As with all multithreaded code, you need to take good care to use the proper locking to avoid race conditions and crashes.




Zero Configuration Networking. The Definitive Guide
Zero Configuration Networking: The Definitive Guide
ISBN: 0596101007
EAN: 2147483647
Year: 2004
Pages: 97

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net