Reputation: 1523
In my Linux app, I have two threads that both try to send a UDP
broadcast packet (around 50-500 bytes) using the same UDP
client socket. They do this about once every 2-3 seconds. In this case, around the "send(...)" clause, I could put pthread_mutex_lock
or pthread_spin_lock
. Theory says that if it's a very small operation, a pthread_spin_lock
is more efficient (despite high CPU consumption for that small amount of time). But if its a larger operation, then pthread_mutex_lock
is better.
Is sending a UDP
packet considered "small enough" to warrant using a pthread_spin_lock
, or should I still stick with pthread_mutex_lock
?
Thanks
Upvotes: 1
Views: 794
Reputation: 22318
Wrapping a system call in a spinlock is a bad idea. The merits of using spinlocks in a user-space app is questionable in any case. The mutex implementation for Linux (using futexes), is very efficient - particularly when a lock is uncontested, which should almost always be the case in well-designed MT apps.
Others have pointed out that the send
function is itself thread-safe.
Upvotes: 1
Reputation: 239011
If the only need for locking is because they're both sending on the same socket, then there's no need for locking at all - it's acceptable for two threads to call send()
on the same UDP socket at the same time. The data sent won't be interleaved.
Upvotes: 3
Reputation: 78903
What you avoid by using a spinlock instead of a mutex is to avoid to go into a syscall in case of a congestion. If you are using the network layer in your critical section, your will be going into a syscall, anyhow. So as far as I can see, using a spinlock makes not much sense, here.
Upvotes: 1