Solved

Multithreading Management

Posted on 2003-10-21
10
277 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 250 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
 
LVL 23

Accepted Solution

by:
Roshan Davis earned 250 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
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
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

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Here is how to use MFC's automatic Radio Button handling in your dialog boxes and forms.  Beginner programmers usually start with a OnClick handler for each radio button and that's just not the right way to go.  MFC has a very cool system for handli…
In this article, I'll describe -- and show pictures of -- some of the significant additions that have been made available to programmers in the MFC Feature Pack for Visual C++ 2008.  These same feature are in the MFC libraries that come with Visual …
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.
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…

747 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now