Why is CPU usage constantly increasing after starting/stopping threads?

杀马特。学长 韩版系。学妹 提交于 2020-01-06 20:25:02

问题


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.

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).

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

(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.)

Edit:

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 is called on the first click, while Stop is called on the next click.


回答1:


Try changing

bool m_continue = false; 

to

volatile bool m_continue = false;

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.



来源:https://stackoverflow.com/questions/31416548/why-is-cpu-usage-constantly-increasing-after-starting-stopping-threads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!