Friday, March 14, 2008

Use volatile variable when control thread procedure closing

When writting a thread procedure , I've written below codes.

BOOL is_running = FALSE;
void thrd_proc(...)
{
while(!is_running)
{
update_windows();
}
}
void exit_program()
{
is_running = FALSE;
CloseHandle(thrd);
}

Thread procedure, thrd_proc is run only is_running is set to TRUE.
thrd_proc's work is update all windows interface.
When closing a program, I call an exit_program function.
An exit_program function set is_running variable to FALSE.
So that a thread procedure can exit an while loop.
That's looks like no problems.

However, when program close, this program will be occure an error.
I could know that still a thread procedure running via debugging.
And is_running value still TRUE.

Because a system optimize an is_running variable via is_running variable moving to CPU register, L1 cache or L2 cache from memory.
Thread access an is_running variable via memory that it's not changed.

To prevent this problem.
I should use volatile variable.
Just add volatile keyword before "BOOL is_running"

volatile BOOL is_running

No comments:

Powered By Blogger