不使用条件变量来唤醒线程的最快方法 [英] fastest way to wake up a thread without using condition variable

查看:155
本文介绍了不使用条件变量来唤醒线程的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试通过设置后台线程来解决一个特定任务来加速一段代码.当需要解决我的任务时,我想唤醒这些线程,执行此工作,然后再次阻止它们等待下一个任务.任务总是一样的.

I am trying to speed up a piece of code by having background threads already setup to solve one specific task. When it is time to solve my task I would like to wake up these threads, do the job and block them again waiting for the next task. The task is always the same.

我尝试使用条件变量(以及需要与它们一起使用的互斥体),但是最终我减慢了代码的速度,而不是加快了代码的速度.主要是因为对所有必需功能的调用非常昂贵(pthread_cond_wait/pthread_cond_signal/pthread_mutex_lock/pthread_mutex_unlock).

I tried using condition variables (and mutex that need to go with them), but I ended up slowing my code down instead of speeding it up; mostly it happened because the calls to all needed functions are very expensive (pthread_cond_wait/pthread_cond_signal/pthread_mutex_lock/pthread_mutex_unlock).

使用线程池(我也没有)是没有意义的,因为它是一个过于通用的结构;在这里,我只想解决我的特定任务.根据实现的不同,我还将为队列支付性能损失.

There is no point in using a thread pool (that I don't have either) because it is a too generic construct; here I want to address only my specific task. Depending on the implementation I would also pay a performance penalty for the queue.

您是否建议不使用mutexcon_var快速唤醒?

Do you have any suggestion for a quick wake-up without using mutex or con_var?

我在考虑诸如定时器读取atomic variable之类的设置线程;如果将该变量设置为1,则线程将执行此工作;如果将其设置为0,它们将进入休眠状态几毫秒(我会从休眠状态开始,因为我想避免使用spinlocks,这对于CPU可能太昂贵了).你怎么看待这件事?任何建议都非常感谢.

I was thinking in setup threads like timers reading an atomic variable; if the variable is set to 1 the threads will do the job; if it is set to 0 they will go to sleep for few microseconds (I would start with microsecond sleep since I would like to avoid using spinlocks that might be too expensive for the CPU). What do you think about it? Any suggestion is very appreciated.

我正在使用Linux,gcc,C和C ++.

I am using Linux, gcc, C and C++.

推荐答案

这些功能应该很快.如果他们花费了大量时间,则很有可能尝试切换线程的次数过多.

These functions should be fast. If they are taking a large fraction of your time, it is quite possible that you are trying to switch threads too often.

尝试缓冲工作队列,并在大量工作积累后发送信号.

Try buffering up a work queue, and send the signal once a significant amount of work has accumulated.

如果由于任务之间的依赖关系而无法实现,那么您的应用程序根本不适合多线程处理.

If this is impossible due to dependencies between the tasks, then your application is not amenable to multithreading at all.

这篇关于不使用条件变量来唤醒线程的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆