在线程争用情况下等待的最快方法
我在 Linux 上使用 pthread。我有一个循环缓冲区将数据从一个线程传递到另一个线程。也许循环缓冲区不是此处使用的最佳结构,但更改它不会使我的问题消失,因此我们将其称为队列。
每当我的队列已满或为空时,弹出/推送操作都会返回 NULL。这是有问题的,因为我的线程会定期触发。等待另一个线程循环会花费太长时间。
我尝试过使用信号量(sem_post、sem_wait),但在争用情况下解锁最多需要 25 毫秒,这大约是我的循环速度。我尝试使用 pthread_cond_t 等待,但解锁最多需要 10 到 15 毫秒。
是否有更快的机制可以用来等待数据?
编辑*
好吧,我使用了条件变量。我使用的是嵌入式设备,因此添加“更多内核或 CPU 功率”不是一个选项。这让我意识到我在各处设置了各种线程优先级,所以我会在进一步处理之前解决这个问题
I'm using pthread on Linux. I have a circular buffer to pass data from one thread to another. Maybe the circular buffer is not the best structure to use here, but changing that would not make my problem go away, so we'll just refer it as a queue.
Whenever my queue is either full or empty, pop/push operations return NULL. This is problematic since my threads fire periodically. Waiting for another thread loop would take too long.
I've tried using semaphores (sem_post, sem_wait) but unlocking under contention takes up to 25 ms, which is about the speed of my loop. I've tried waiting with pthread_cond_t, but the unlocking takes up to between 10 and 15 ms.
Is there a faster mechanism I could use to wait for data?
EDIT*
Ok I used condition variables. I'm on an embedded device so adding "more cores or cpu power" is not an option. This made me realise I had all sorts of thread priorities set all over the place so I'll sort this out before going further
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您应该使用条件变量。唯一更快的方法是特定于平台的,而且它们的速度只能忽略不计。
您看到的性能很差,只是因为您的线程被取消调度。当您的线程接近其时间片末尾并且调度程序允许未阻塞的线程抢占正在运行的线程时,您会看到很长的“延迟”。如果您的核心数多于线程数或将线程设置为更高的优先级,则不会看到这些延迟。
但这些延迟实际上是一件好事,您不应该担心它们。其他线程也有机会运行。
You should use condition variables. The only faster ways are platform-specific, and they're only negligibly faster.
You're seeing what you think is poor performance simply because your threads are being de-scheduled. You're seeing long "delays" when your thread is near the end of its timeslice and the scheduler allows the unblocked thread to pre-empt the running thread. If you have more cores than threads or set your thread to a higher priority, you won't see these delays.
But these delays are actually a good thing, and you shouldn't be concerned about them. Other threads just get a chance to run too.