Http://www.codeproject.com/threads/threads_and_mfc.asp
Introduction
This article is written to those who are beginners with The multithreading programming and I have tried to initialize strate some issues in this connection, and hope that it will be a good help for the beginners. it controls strates how threads can be created and shows how the amount of processor time for each thread varies due to the Code in the Threads' functions.
Threads
A thread is a basic unit to which the operating system allocates processor time and is the smallest piece of code that can be scheduled for execution. an application written for Windows consists of one or more processes and a process is an instances of an executing program. A thread runs in the address space of the process and can use the resources which are allocated to the process. A process always has at least on thread of execution and it's known as the primary thread. all threads in MFC applications are represented by cwinthread
objects. the primary thread of MFC applications is implemented as a class derived from cwinapp
, which itself is derived directly from cwinthread
class.
It is important to consider that the threads do not run concurrently (I refer to systems with just one central processing unit), but it seems that they run at the same time, the reason is that the Code Execution switches quickly between threads. whenever a thread uses its time slot, it shocould wait for its next turn to complete or continue its code execution. during the time the thread is not active, the code execution is going on in another thread, which becomes the current thread of the application. I will describe this with an example in the following:
Suppose you cocould create 5 threads in your application and each of these threads were capable of saying their thread's numbers, whenever they got their time slot. if so then it wocould be possible to hear the current thread's numbers coming out of the speaker.
The important fact in the example is that we can distinguish between different numbers coming out of the speaker, and if the threads ran at the same time we cocould not distinguish between the numbers, because then all the numbers shocould be heard at the same time and it wocould not be possible to hear the numbers separately. at the end of this article I'll show you, how you can make such an application and hope it gives you a good understanding of the fact.
In contrast to Win32 API, MFC distinguishes between two types of threads:
1-worker threads
These type of threads are used to complete background tasks when there is not a need for any user input. an example can be database backup functions. A worker thread can be created by implementing a function that performs the task your thread is to perform and passing the address of this function toAfxbeginthread (...)
Function. The worker thread's function shocould have the following syntax:
Uint yourfunction (lpvoid pparam );
I will explain more about this in the demo application...
2-User Interface threads
These types of threads are able to handle user input and they implement a message map to respond to events and messages generated by user interaction with the application. to create a user interface thread, you must derive your own class fromCwinthread
Class and pass run-time information about the class toAfxbeginthread (...)
Function.
About the demo application:
As mentioned before for a worker thread, you define a function and decide the responsibility of your function in the thread. in the demo app. you can create 5 different worker threads with 2 responsibilities for each worker thread's function:
1-drawing the corresponding thread's number 80 times into the applications main window.
2-showing a part of the code being executed, whenever the corresponding thread is running.
A variable loop is used in this function to force the operating system to obtain variable time slice for each thread's execution, you can change the loop's factor with the use of Slider controls, which are associated with the threads and observe, how this change affects the speed of the corresponding thread. the threads 'numbers has different colors when they are drawn to the applications main window. when you create worker threads, you can see that the progress of the threads (Code being executed in the loop) and the appearance of thread numbers in the applications main window, switches both among the running threads and threads numbers, indicating that the Code Execution switches from current thread to other threads, which have been waiting for their turn to use their time slice for completion of their code in their functions.
When the threads are running, the numbers from 1 to 5 with their corresponding colors appear on the screen, and it gives a good picture of the running threads in real time. the following image shows the worker threads on the fly.
The picture shows that the code execution has been switched from thread 1 to thread 2, and from thread 2 to thread 3 and from thread 3 to thread 4, and the screen shot is taken before the creation of thread 5. the interesting fact is that during the activation time all of the 5 threads including the primary thread of the application have been running (multithreading concept ), but at any point in the thread's activation time only one of these threads has been active and the others have been waiting for their turn to continue their code execution. the picture shows only the time during which the worker threads have been active, and does not show any picture of the other threads, which have been running in the system, but we have a prove for application's primary thread and that's this screen shot, and if the application's primary thread was not running it wocould not be possible to take this screen shot. the primary thread is active until the application's execution is stopped.
As the picture shows the competition between the running threads for ending their work (completion of their code) First, is not a fair one, as in the program, thread 1 is created first, and its obvious that thread 1 ends first and wins the competition. but the result of this competition is not always the same, and sometimes although thread 1 is created first and runs first, it can not win the competition, because it depends on the amount of work each thread is going to do. sometimes like this case the work of the worker function in thread 1) is just to execute a short loop, and so it can finishes it's work before the program scope is switched to the other waiting threads, and the very first time slice for thread 1 has been long enough to complete it's work. but if the work is more (longer loop) thread 1 shoshould also go to a waiting state, until it gets its turn back, and because the return of the program scope to the waiting threads is not always the same, so there wocould be an equal chance for every thread to win the competition. the next picture shows that although thread 5 has been created and run last, it has won because the worker function (in thread 1) in this case has been more complicated than before and thread 1 has not been able to complete it's work during its first time slice, and it did go to a waiting state like the other threads, and so there has been a fair competition this time.
You may try this demo app. if you are beginner and view how the threads behave. you can change the loop factor in the worker thread's function and view, how it affects the activation time of the threads. you can see that the more is the loop factor, the more is the worker thread function's responsibility (longer loop to execute) and so the more time will be necessary, and so the activation time will increase. using the "Task Manager", keep eye on the CPU's usage, and you can see, that it increases rapidly during the activation time of the threads. try to open another program for example MS word, when the threads are running, and you can see that it takes a longer time for MS word to open, and the threads speed also decreases after opening MS word.
Now let's start to make an application with user interface threads:
As I promised at the begining, I will guide you in making an application which has user interface threads, and the code associated with these thread's are responsible for creating sound, saying their threads number, such that we are informed which of the threads are the current thread of the application.
Step 1:
Using the Appwizard, create a dialog based application by choosing the "dialog based" in the step 1 of the wizard and click Finish.
Step 2:
As explained before, we have to drive our own class derived fromCwinthread
Class and pass run-time information about the class to the user interface versionAfxbeginthread (...)
Function, so open the Class View, write click on the classes (yourprojectname class) and choose"NEW class"From the Pop Up menu.
Step 3:
From the "New Class" dialog box, create a new class with cwinthread as"Base class"
And use MFC class as"Class Type"And enter a name for this class .(Cyourthreadclassname).
Step 4:
Save your project and look at the newly created class from the Class View, inspect the source code for your Thread class. Note that the wizard has provided stub ImplementationInitinstance ()
AndExitinstance ()
Functions and in these function you shoshould add your class-specific implementation code. you may notice also that a message map is implemented for your Thread class (as explained before the user interface threads implement a message map to respond to events and messages .)
Step 5:
If the Thread class shocould respond to the user events it shocould be associated with an user interface object and we use an object of cdialog class. So create a dialog resource and associate it withCdialog
Class .(Cyourdialogclassname
)
Step 6:
Open the Class View, expand your newly created dialog class and double click on the constructor function. Call the create function in this function as below:
Create (yourdialogresourceid, null );
You find your dialog resource ID from the "dialog properties" by entering on the dialog resource from the keyboard or by Right clicking on the dialog resource and choosing properties from the POP op menu.
Step 7:
Click on Class View, expand the Thread class and double click onInitinstance ()
Function. Now we create a dialog object in this function and assignM_pmainwnd
Member variable of the thread class to this object. (by doing this, our Thread class associates with a user interface object). Add the following code intoIniinstance ()
Function.
M_pmainwnd =NewCyourdialogclassname; m_pmainwnd-> setforegroundwindow (); m_pmainwnd-> showwindow (sw_show );
Remember to include the header file of your dialog class to the currently opened file.
Step 8:
It will be a god idea to make an arrayCwinthread
Pointers and assign these pointers to the created threads, so it wocould be easy to get our thread objects whenever necessary so open the Class View, double click onCyourprojectnameapp
Class and in the class definition Add the following code:
Cwinthread * m_pthread [5];
(Remember to add:ExternCyourprojectnameapp theapp;
At the bottom of the currently opened file, afterDeclare_message_map ()};
)
Step 9:
Put a button in the main dialog window in order to create and run the user interface threads.
Step 10:
With this new button selected, open the Class Wizard by enteringCTRL + WFrom the keyboard, and make a command handler function.
Step 11:
Open this newly created handler function and add the following code in order to create 5 user interface threads:
For(IntI =0; I <5; I ++) theapp. m_pthread [I] = afxbeginthread (runtime_class (cyourthreadclassname ));
(Remember to include the header file of your Thread class (Yourthreadclassname. h
) At the top of the currently opened file)
That's it, save your project and build it.
By now, we can create 5 user interface threads by clicking on the button in the main dialog window, and we can see that 5 dialog windows (You may move the upper dialog in order to see the other created dialog windows) have been created. now we need to define threads responsibilities, and that is to hear the corresponding thread numbers, talked from each thread, whenever the thread becomes active, so let's do that:
Step 12:
Open the resource view and double click on the dialog resource ID of your newly created dialog, in order to open the dialog editer.
From the main menu choose:
PRoject->ADd to project-> comPOnents and controls...
Step 13:
Now the "components and controls Gallery" shocould be opened, double click on the registered ActiveX controls folder. Choose and insert the texttospeech class and close the "components and controls Gallery ".
Step 14:
Now this new control shoshould appear among other controls in the dialog editor. drag this control and insert it into the dialog resource. using Class Wizard Add a member variable to this "texttospeech" control. you may call itM_speaker
.
Step 15:
Open Class View, right click on the class which is associated with your newly created dialog Resource (User Interface windows) and choose "add member variable" from the pop up menu. create a new variable with nameM_threadnr
And with the typeCstring
.
Step 16:
Open the Class View and expand the dialog class and double click on the constructor function (Yourdialogclassname ()
), Add the following code in to this function
Collapse
// You have already written this line in Step 6 Create (yourdialogresourceid, null ); Int Static Nr = 1 ; Cstring S; Char Buf [ 10 ]; ITOA (NR, Buf, 10 ); S = "Thread #" ; S + = Buf; S + ="Dialog window" ; Setwindowtext (s ); Switch (NR ){ Case 1 : {M_threadnr = "1" ; Break ;} Case 2 : {M_threadnr = "2" ; Break ;} Case 3 : {M_threadnr = "3" ; Break ;}Case 4 : {M_threadnr = "4" ; Break ;} Case 5 : {M_threadnr = "5" ; Break ;} Break ;} // We Want To Be informed which thread is the current thread after 1 second Settimer (NR, 1000 , Null); NR ++;
Step 17:
Open the dialog Resource (associated with the user interface threads), right click on the dialog resource and choose events.
ChooseWm_timer
And click Add and edit.
Step 18:
Add the following code inOntimer ()
Handler function:
Cstring STR ="Thread"; STR + = m_threadnr; m_speaker.speak (STR );// You may delete this line if you want to hear the threads continuouslyKilltimer (nidevent );
That was all, save your work and build the project and try it. as you can see from the code after each second the current thread of the application says it's thread's number. although there are more threads and details involved in this example, it usually strates that only one thread at a time is active.
as you may have seen in the demo app. when you increase the loop factor in a worker thread's function, that function uses more time to complete the code execution. you can use your project to cause the same effect by increasing a participant thread function's responsibility (for example putting a loop to be executed ), by doing this you will hear that participant thread more often than the other threads and not just one time. replace the code in the ontimer ()
handler function by the following code and retry your project.
Cstring STR ="Thread"; STR + = m_threadnr; m_speaker.speak (STR );IntI = atoi (m_threadnr );If(I =3){For(IntJ =0; J <3; J ++) m_speaker.speak (STR );}// You may delete this line if you want to hear the threads continuouslyKilltimer (nidevent );
If you have a problem with stopping the threads voice after you have stopped the application, open the task manager and end the process with the name "vswitch.exe ".
As I mentioned before, the user interface threads are able to handle user input and they implement a message map to respond to events and messages generated by user interaction with the application. so you can give more functionality to the threads by implementing message handler functions, as an example you can make a handler function, which stops the threads to talk (by callingM_speaker.stopspeaking ();
In your handler function), whenever you click into the threads window and so on.
I hope that this article was useful for you.