I think that there should be a page in the libpcap manual that
explicitly explains the multithreading capabilities and limitations.

Some libraries have an entry in the manual stating that the library is
not threadsafe at all. Nine times out of ten, you're safe to use these
libraries from multiple threads so long as you use an exclusive lock.

Some other libraries are thread-safe but the manual states that the
handle returned from the 'open' function can only be used by one
thread. With most of these libraries, you're safe to use the handle
from multiple threads so long as you use an exclusive lock. With some
other libraries however, you can't even do this because the library
might use thread-local storage for each handle.

I remember seeing a page somewhere on the internet that read something
along the lines of:
"The libpcap library is thread-safe, i.e. multiple threads can call
libpcap functions concurrently. However once you've obtained a handle
from pcap_open_live, that handle can only be used exclusively by one
thread -- with the exception of the pcap_breakloop function".

I've been searching and searching for this webpage again but I can't
find it. I can't remember where I saw it. Is the above paragraph true?

Is it safe to use a pcap_t* handle from multiple threads if you use an
exclusive lock though? Or is this still forbidden even if you use an
exclusive lock?

I think the debug build of libpcap should have runtime asserts to
ensure that the same thread is always operating on any given pcap_t*
handle. For example there could be a global map of pcap_t* handles to
thread ID's, something like:

    struct Mapping {
        pcap_t    *handle;
        pthread_t  thread_id;

    Mapping mappings[32u];

The thread_id could start out as NULL until the first pcap function is
called, at which point it gets set to the ID of the current thread.
And after that, every other pcap function could make sure that it's
always the same thread. So each pcap function could begin with the

    if ( NULL == mappings[i].thread_id ) mappings[i].thread_id = pthread_self();

    assert( pthread_self() == mappings[i].thread_id );

I've been using a program of my own for the past 13 years, and it uses
the same pcap_t* handle from two threads. One thread does all the
receiving, and the other thread does all the sending. So far I haven't
had in crash -- in 13 years -- but if I really should have two
separate handles then I'll change my code.
tcpdump-workers mailing list -- tcpdump-workers@lists.tcpdump.org
To unsubscribe send an email to tcpdump-workers-le...@lists.tcpdump.org

Reply via email to