Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

Multithreading Management

Posted on 2003-10-21
10
Medium Priority
?
286 Views
Last Modified: 2013-12-03
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 program...it is available immediately...otherwise...it 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.
0
Comment
Question by:SGyves
  • 3
  • 3
  • 2
  • +2
10 Comments
 
LVL 4

Assisted Solution

by:inox
inox earned 1000 total points
ID: 9595219
Hi,
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.

0
 

Author Comment

by:SGyves
ID: 9595368
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 reality...my 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 request....to 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.
0
 
LVL 86

Expert Comment

by:jkr
ID: 9595507
>>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.
0
Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
LVL 23

Accepted Solution

by:
Roshan Davis earned 1000 total points
ID: 9596443
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)

eg:

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

HANDLE g_hEvent = CreateEvent(NULL,
                                            FALSE,
                                            FALSE,
                                            NULL);

INT      g_hHowManySeconds = 120000;


BOOL CIdleTestApp::OnIdle(LONG lCount)
{

      SetEvent(g_hEvent);

      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);      
            }

            ResetEvent(g_hEvent);
      }
}

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

Expert Comment

by:AlexFM
ID: 9596546
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);
0
 
LVL 4

Expert Comment

by:inox
ID: 9597914
Hi,
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.
0
 
LVL 48

Expert Comment

by:AlexFM
ID: 9597936
Sleep has no sence if main thread is in idle state, this just slows down worker thread.
0
 
LVL 4

Expert Comment

by:inox
ID: 9598654
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.
0
 

Author Comment

by:SGyves
ID: 9599401
Yes...this instruction I do...and then sleep for 10ms...it looks like this:

if(!(dPtr->IsIncommingEmpty))
{
               vPtr->PostMessage(IRC_DISPLAY_MESSAGE);
}
Sleep(10);

The main UI thread does the rest...it 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 user...it has a sleep time of 250ms...which seems to balance out fine...as larger chunks of messages can be recieved (many lines at once) in one itteration.
0
 

Author Comment

by:SGyves
ID: 9599557
I am splitting the points between rosh and inox for good explanations and code samples of excellent Thread Management concepts.
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction: Ownerdraw of the grid button.  A singleton class implentation and usage. Continuing from the fifth article about sudoku.   Open the project in visual studio. Go to the class view – CGridButton should be visible as a class.  R…
Ready to get certified? Check out some courses that help you prepare for third-party exams.
This video will show you how to get GIT to work in Eclipse.   It will walk you through how to install the EGit plugin in eclipse and how to checkout an existing repository.
If you’ve ever visited a web page and noticed a cool font that you really liked the look of, but couldn’t figure out which font it was so that you could use it for your own work, then this video is for you! In this Micro Tutorial, you'll learn yo…

886 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question