[Winpcap-users] Using threads.

Guy Harris guy at alum.mit.edu
Wed Mar 15 19:15:15 GMT 2006


David Barnish wrote:
> Just my opinion from quickly looking at the code, but I think your
> problem is thread contention/context switching.
> 
> For each thread, you have an endless loop that calls pcap_next_ex(),
> processes the packet, then immediately loops and does the same thing.
> Each thread will be trying to run non-stop and processing incoming
> packets until the OS forces it out of the CPU queue so another thread
> can run. This is similar to two threads running a function like this at
> the same time:
> 
> While(true)
> {
> 	Printf("Hello World.\n");
> }
> 
> Both threads are trying to use system resources and are not giving up
> control voluntarily.
> 
> My suggestion is to use the pcap_dispatch() function (or something
> similar) so the thread will sleep for a bit, then wake up and process
> multiple packets.

The thread will only sleep in pcap_dispatch() if there are no packets 
available to be read at that instant.

The same is true for pcap_next_ex(); the only difference between a loop 
using pcap_dispatch() and a loop using pcap_loop_ex() is that the loop 
using pcap_dispatch() could process more than one packet per 
pcap_dispatch() call while the loop using pcap_loop_ex() processes only 
one packet per pcap_loop_ex() call.

"Processes" here means "hands to the callback" in the case of 
pcap_dispatch() and "returns to the caller" in the case of 
pcap_next_ex().  Both pcap_dispatch() and pcap_loop_ex() ultimately call 
the read op for the pcap_t; in WinPcap, the read op:

	checks whether there are any packets left in its buffer and, if there 
aren't, reads a new batch of packets into the buffer - that read might 
return immediately or might block;

	processes all the packets in the buffer if called with a count argument 
of -1, or processes no more than the number of packets specified with a 
positive count argument.

pcap_next_ex() calls it with a count of 1; pcap_dispatch() calls it with 
the count specified to pcap_dispatch().

So there won't be a difference between the two loops with regard to when 
they sleep - they'll sleep if the kernel code blocks waiting for enough 
packets to arrive or for the timeout to expire.

The pcap_next_ex() loop makes more calls to the read op, as each call 
asks it to process only one packet from its buffer, so it might consume 
more CPU time; that's the only difference you should see.

> Another method would be to get the read event for the interface and put
> a WaitForSingleObject() call at the top of the loop, waiting on this
> event and using a timeout of 500 milliseconds or so. In this way, the
> thread would voluntarily give up control for a short time

Not if there are packets ready to be read.


More information about the Winpcap-users mailing list