Multithreading Management

Those of you who have followed my questions know that my program deals a lot with multithreading. I don't think it will stop there either. I am downloading files...polling variables....connecting sockets and communication between processes. What I need more information on is managing all these threads. Specifically, how to make certain things a priority in my program. I need to know how I can give priority in the following order:

Main Thread (UI):
Communications Thread(Socket):
Trigger display messages thread(Polling For Incomming Messages):

What this means is that I want, above all, all UI messages processed first....then when there are no UI messages to process...I want the work to be divided evenly among the communications and displaying of messages. So if the user wants to do something with the is available is recieving messages from the socket and the Trigger Display Messages Thread is polling for things to display and displaying them as fast as possible.

Can anyone tell me how to achieve that. A small explanation or a good reference would be great. The only thing I ask is to not give me pages of code to look through for the answer. I would love any help I could get with this. Thank everyone who has followed up on my questions for all the continuing help.
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

CPU-time is granted to threads (in time-slices) by the system-sceduler and he does that best he can, applications cannot absolutely control the running-states of thread, but they can assign threadpriorities which the sceduler cares about.
What does the mainthread?
Usually the mainthread (in WIN, MFC Programs) is dispatching he messageloop. Without a message and WIN Program does nothing. That means the mainthread hangs in a GetMessage-function until a message is received. The (waiting) GetMessage disposes the mainthread, a disposed thread does not get CPU-time, it is not runnable, so other threads (of your program, and other running programs of course too) get cpu-time, and now it depends on the:
a) runnable state and b) on the threadprioriy wich thread gets cpu-time. Threa are several things who make a thread not runnable i.e: GetMessage, WaitFor...Object, Sleep(), some Readfile() versions, blocking Socketfunctions etc.
Generally, a (well behaving) thread who has no effective work to do should be suspended (hang in a waiting function) especially if he has higher priority.

If you want the main-thread being preferred for execution, so give other threads a lower priority, thats it, and if there are workerthreads with no blocking calls, let them Sleep an while, otherwise you cause a system load of 100%.

An other problem is thread-termination, you must find the way to free threads from there blocking function, because an application should terminate all threads gracefully.

SGyvesAuthor Commented:
Is there a way to say to a loop..."Ok do this work...but if the user is requesting some UI operation...yeild control to the main thread" In program will never be under a heavy load situation unless a long "LIST" operation is requested from the server my socket is connected to. If that happens....There will be many lines recieved and many lines to display....otherwise....typically...a message every second or so...not very heavy at all. I simply want to avoid any situation where one of my threads will not yield to the UI...but whne there are no UI just go all out and do their thing as fast as they can. Sleep is probably the best method. One thing I noticed is that when I brought the sleep times down to a low number (like Sleep(10)) my UI was extremely responsive and everythng seemed to work wonderful. Is there anything wrong with doing that?? Let me know.
>>Is there a way to say to a loop..."Ok do this work...but if the user is requesting some UI
>>operation...yeild control to the main thread"

Actually, you would measure the "message load" to your app (they come with time stamps, so that should be easy) and schedule the priority of your worker threads accordingly usin 'SetThreadPriority()' - but, keep in mind that they have some I/O load to cope with.
Amazon Web Services

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

Roshan DavisCommented:
You mean, you want to do background processing while  your program is idle?

You can use ur App class's OnIdle (your CWinApp derived class)


// Global declarations
HANDLE g_hThread;
DWORD WINAPI IdleCntThread(LPVOID lpParam);

HANDLE g_hEvent = CreateEvent(NULL,

INT      g_hHowManySeconds = 120000;

BOOL CIdleTestApp::OnIdle(LONG lCount)


      return CWinApp::OnIdle(lCount);

void CIdleTestApp::StartThread()

      DWORD dwThreadId;

      g_hThread = ::CreateThread(NULL, 0, IdleCntThread,
                                             (LPVOID)this, 0, &dwThreadId);

DWORD WINAPI IdleCntThread(LPVOID lpParam)
      DWORD      dwStart;
      DWORD      dwEnd;

      while ( TRUE )
            dwStart = GetTickCount();

            WaitForSingleObject(g_hEvent, g_hHowManySeconds);
            dwEnd = GetTickCount();

            if ( g_hHowManySeconds <= (dwEnd - dwStart) )
                  ::MessageBox(NULL, "Idle Notification", "Idle", MB_OK);      


This program will notify when the user is 2 minutes Idle.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Try to reduce worker thread priorities to THREAD_PRIORITY_IDLE (you can do this when thread is created) and to increase main thread priority to THREAD_PRIORITY_ABOVE_NORMAL or THREAD_PRIORITY_HIGHEST using SetThreadPriority:

SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST);
Is there a way to say to a loop..."Ok do this work...but if the user

Yes, and this is done automatically if the thread has a lower priority than the mainthread, so do don't have to program anything to achive that.
A Sleep of 10 is ok, and its also good if you can break the threadcode in small pieces (with a sleep) as its obvious not to make big sense if the Sleep call is reached only once an hour.
Sleep has no sence if main thread is in idle state, this just slows down worker thread.
I think Sleep makes sense due to the following:
- wherefrom the workerthread should know the mainthread being idle
- programs (and threads) should bargain for other programs (and threads) want to run too.
- imagin a loop polling for the presence of a telegram, with a Sleep of 10 does it ~100 times a second, without the Sleep maybe 100000 times a second, where is the sense, this thread will cause a max cpu-load for doing mostly nothing.
SGyvesAuthor Commented:
Yes...this instruction I do...and then sleep for looks like this:


The main UI thread does the simply notifies the main thread that there is something to display...probably shorter than the sleep time.

My other thread recieving messages and taking sends from the has a sleep time of 250ms...which seems to balance out larger chunks of messages can be recieved (many lines at once) in one itteration.
SGyvesAuthor Commented:
I am splitting the points between rosh and inox for good explanations and code samples of excellent Thread Management concepts.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Fonts Typography

From novice to tech pro — start learning today.