简体   繁体   中英

Should I use spin_lock or mutex_lock for this particular situation?

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

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM