简体   繁体   English

在这种特殊情况下,我应该使用spin_lock还是Mutex_lock吗?

[英]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. 在我的Linux应用程序中,我有两个线程都尝试使用相同的UDP客户端套接字发送UDP广播数据包(大约50-500字节)。 They do this about once every 2-3 seconds. 他们大约每2-3秒执行一次此操作。 In this case, around the "send(...)" clause, I could put pthread_mutex_lock or pthread_spin_lock . 在这种情况下,可以在“ send(...)”子句周围放置pthread_mutex_lockpthread_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). 理论上说,如果这是一个非常小的操作,则pthread_spin_lock会更有效率(尽管在这么短的时间内会消耗大量CPU)。 But if its a larger operation, then pthread_mutex_lock is better. 但是,如果其操作较大,则pthread_mutex_lock更好。

Is sending a UDP packet considered "small enough" to warrant using a pthread_spin_lock , or should I still stick with pthread_mutex_lock ? 是否正在发送UDP数据包“足够小”以保证可以使用pthread_spin_lock进行授权,还是我仍应坚持使用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. 如果唯一需要锁定的原因是它们都在同一套接字上发送,那么根本就不需要锁定-两个线程同时在同一UDP套接字上调用send()是可以接受的。 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. Linux的互斥体实现(使用futexes )非常有效-尤其是在无争议的锁的情况下,在设计良好的MT应用程序中几乎总是如此。

Others have pointed out that the send function is itself thread-safe. 其他人指出, send函数本身是线程安全的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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