Why is CPU usage constantly increasing after start

2019-08-30 02:38发布

问题:

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.