Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

线程池“惊群”现象 #15

Open
lyykjen opened this issue Mar 10, 2018 · 1 comment
Open

线程池“惊群”现象 #15

lyykjen opened this issue Mar 10, 2018 · 1 comment

Comments

@lyykjen
Copy link

lyykjen commented Mar 10, 2018

pthread_mutex_t lock;
pthread_cond_t cond;

https://github.com/zyearn/zaver/blob/master/src/threadpool.h#L29-L30

线程池结构中只有一对互斥锁和条件变量,生产者线程每添加一个新任务,都会调用 pthread_cond_signal 一次,所有线程都会等待同一个cond, 但最终只有一个消费者线程从队列里拿到任务去执行,其他线程被唤醒带来不必要的线程调度开销,这就是惊群现象的根源所在,并且是消费者线程数量越多,惊群现象越严重----意味着 CPU 占用越高,线程池的调度性能越低。

一个解决方法是,在共用同一个互斥锁情况下,给每一个消费者线程创建对应的线程条件变量,这样生产者线程有新任务并找到空闲消费者线程时候,将任务添加到队列中并只通知该消费者线程。线程条件变量的通知过程是定向的,未被通知的消费者线程不会被唤醒,这样惊群现象也就不会产生了。

@lzw-all-in
Copy link

@lyykjen 实际上pthread_cond_signal并不会产生惊群现象。每次只是从wait_cond队列中取出一个线程唤醒而已

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants