为什么启动/停止线程后CPU使用率不断增加? [英] Why is CPU usage constantly increasing after starting/stopping threads?

查看:22
本文介绍了为什么启动/停止线程后CPU使用率不断增加?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个程序,通过单击按钮,将创建一个新线程(如果它不存在)并建立与相机的连接.现在考虑这个相同的流程,但有 N 个摄像头(因此在点击时创建 N 个线程).再次单击按钮后,所有先前创建的线程都被告知停止执行(通过布尔标志),然后在每个线程上调用 Join(500) - 结束所有线程.

I have a program where on a button's click, a new thread will be created (if it didn't exist already) and a connection to a camera is established. Now consider this same flow, but with N number of cameras (thus creating N threads on click). After the button is clicked again, all of the previously created threads are told to stop executing (through a boolean flag), and then Join(500) is called on each one - ending all threads.

现在,我注意到在很短的时间间隔内执行的连续点击不仅会增加 CPU 使用率(当 8 个线程运行时正常),而且即使在线程应该从调用 Join(500).

Now, I have noticed that successive clicks performed within a short time interval not only bump CPU usage (normal when the 8 threads are running), but also keep that usage at the same level even after the threads have supposedly ended from the call to Join(500).

什么可能导致即使在加入线程后 CPU 使用率仍然很高?

What could be causing the CPU usage to remain high even after the threads are joined?

(注意:我也尝试过 TPL 的 Task.WaitAll() 实现并观察到相同的场景,所以我想说这不是由线程以某种方式没有停止执行引起的.)

(Note: I have also tried the TPL's Task.WaitAll() implementation and observed the same scenario, so I want to say that this is not caused by the threads somehow not stopping execution.)

Thread[] m_threads = new Thread[8];
void Start()
{
    for (int i = 0; i < m_threads.Length; i++)
    {
        m_threads[i] = new Thread(() =>
        {
            while (m_continue) { ... }
        });
    }
}

bool m_continue = false;
void Stop()
{
    m_continue = false;
    for (int i = 0; i < m_threads.Length; i++)
    {
        m_threads[i].Join(500);
    }
}

在第一次点击时调用 Start,而在下一次点击时调用 Stop.

Start is called on the first click, while Stop is called on the next click.

推荐答案

尝试更改

bool m_continue = false; 

volatile bool m_continue = false;

根据您的描述,我假设 m_continue 被缓存(在寄存器或其他地方),因此永远不会改变,即使您在 Stop() 方法中分配它.

According to your description, I assume m_continue gets cached (in a register or whatever) and thus never changes, even when you assign it in Stop() method.

这篇关于为什么启动/停止线程后CPU使用率不断增加?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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