Click here to Skip to main content
15,881,882 members
Articles / Programming Languages / C++
Article

Simple Multithreaded Application in pure C, Win32 and MFC

Rate me:
Please Sign up or sign in to vote.
4.07/5 (58 votes)
30 Nov 2003CPOL5 min read 344.3K   19.8K   139   33
This article explains how to create simple multithreaded applications in C Run Time Library, Microsoft Foundation classes and Win32 API functions.

Introduction

A thread is a path of execution. A process requires at least one thread. But, it may contain more then one thread. If the process is closed, all the threads in that process are killed automatically. When we create a thread in an application that is actually a secondary thread. In C or C++ the program entry point is main or wmain (Unicode version). In windows application the program starts in WinMain or wWinMain. When the program starts, the operating system creates the first thread. Because, Windows is a multitasking operating system.

Thread function

Thread function is like an ordinary function with long void pointer parameter. We can pass any data through void pointer data type.

A simple thread function looks like

ThreadFunction(LPVOID param)
{
    // do somthig

    ......
    .......

    //return value;

}

Thread Priorities

The thread priority controls the thread process priority. The thread priorities are following.

  • Highest THREAD_PRIORITY_HIGHEST
  • Above Normal THREAD_PRIORITY_ABOVE_NORMAL
  • Normal THREAD_PRIORITY_NORMAL
  • Below Normal THREAD_PRIORITY_BELOW_NORMAL
  • Idle THREAD_PRIORITY_IDLE

We set thread priority with the CreateThread function. We get or set thread priorities in GetThreadPriority and SetThreadPriority Win32API functions or CWinThread’s functions which we call freely in the code. The priority functions return a BOOL value.

C Run Time Library Multithreading

_beginthread
_beginthreadex
_endthread
_endthreadex

All the above c run time library functions are in the process.h header file. Make sure the Microsoft Visual Studio project setting is as multithreaded DLL. The _beginthread and _beginthreadex functions are used to create threads in C run time library. But, these functions have some differences. The _beginthreadex has some add ional parameters like security and thread address. When we create thread using _beginthread we end the thread use _endthread. The _endthread closes thread handle automatically. But, if we use _endthreadex we close the nthread handle using CloseHandle Win32 API function. The C Run Time Library contains the Thread Local Storage (TLS) internally. We can use thread local storage using API or Compiler specific code. The TlsAlloc, TlsFree, TlsGetValue and TlsSetValue are used to store thread specific data. Microsoft recommend that If you use _beginthread functions for C run Time Library you can not use Win32 API like ExitThread or CreateThread. Because, if use that method it might result in deadlocks. _beginthread uses multiple arguments in the thread creation. Our example program is a simple console based application. The user enters number of threads to create and then we execute each thread.

// Secound Thread function
void ThreadProc(void *param);

// First thread
int main()
{

    int n;
    int i;
    int val = 0;
    HANDLE handle;

    printf("\t Thread Demo\n");

    printf("Enter the number of threads : ");
    scanf("%d",&n);


    for(i=1;i<=n;i++)
    {
        val = i;
        handle = (HANDLE) _beginthread( ThreadProc,0,&val); // create thread
        WaitForSingleObject(handle,INFINITE);


    }


    return 0;
}


void ThreadProc(void *param)
{

    int h=*((int*)param);
    printf("%d Thread is Running!\n",h);
    _endthread();

}

The thread waits for completion of another thread using WaitForSingleObject Win32 API function.

MFC Multithreaded

The CWinThread is the base class for all thread operations. MFC supports two types of threads. These are User Interface Thread and Worker thread. The user interface thread is based on windows message. The worker thread runs in the background process. (Examples, search a file in the find window or communicate with web browser in the web server) . The CWinThread supports both worker thread and User interface Threads. But, we will discuss only worker threads.

The MFC class hierarchy

CObject
    CCmdTarget
        CWinThread
            CWinApp

In the above class hierarchy the CWinApp application class is derived from CWinThread. So, if we create a application the thread is also created. If we create a thread, that is a secondary thread. The mother class CObject has some features like, Serialization support, Run time Class information and Debugging support. The derived class CWinThread also has the same features. The most common useful data members and member functions are the following.

Data members

  • m_hThread The current thread handle
  • m_bAutoDelete Whether the thread has set to auto delete or not
  • m_nThreadID The current thread ID

Data Functions:

  • CreateThread Start the exec execution of thread
  • SuspendThread Increment thread suspend count. When the resume thread occur only the thread resume.
  • ResumeThread Resume the thread. Decrements the thread count stack
  • SetThreadPriority Set thread priority ( LOW, BELOW LOW or HIGH)
  • GetThreadPriority Get the thread Priority

Not all the member functions in MFC as class members. We can access some functions globally also. These functions begin with Afx. The AfxBeginThread, AfxEndThread are most widely useful functions in MFC thread. We create thread using AfxBeginThread function. AfxBeginThread Syntax:

CWinThread* AfxBeginThread( AFX_THREADPROC ThreadProc, LPVOID Param,
      int nPriority = THREAD_PRIORITY_NORMAL,UINT nStackSize = 0,
      DWORD dwCreateFlags = 0, LPSECURITY_ATTRIBUTES lpSecurityAttrs = NULL );

The ThreadProc is first Parameter in AfxBeginThread function. We use name of thread function in this parameter. We pass the void pointer arguments in this function. The return type in the function is UINT. The other arguments in AfxBeginThread are optional. The default thread priority is THREAD_PRIORITY_NORMAL. We can change this any time using CwinThread SetThreadPriority function. We also get the thread priority.

The Thread terminates using AfxEndThread. The AfxEndThread has a Exit code argument list.

CwinThread *pThread = AfxBeginThread( ThreadFunction, &data);


UINT ThreadFunction(LPVOID param)
{
    DWORD result =0 ;

    // do somthig

    AfxEndThread(exitCode);
    return result;

}

Win32 Multithread

Win32 Thread created by CreateThread function. The syntax in CreateThread is following

HANDLE CreateThread(  LPSECURITY_ATTRIBUTES lpThreadAttributes,
            DWORD dwStackSize, LPTHREAD_START_ROUTINE lpStartAddress,
            LPVOID lpParameter,  DWORD dwCreationFlags, LPDWORD lpThreadId);

We terminate thread using the following methods.

  1. use TerminateThread function
  2. use ExitThread function
  3. use return

But, Advanced Windows by Jeffery Ritcher recommends us to use the return method. TerminateThread or ExitThread function does not clear the Thread Stack properly. The GetThreadTimes is used to find the thread’s run time. The GetCurrentThreadID is to get current thread ID. The Sleep function is to sleep a particular thread for so many milliseconds. Example Sleep (1000) will sleep the thread for 1000 milliseconds. The SwithToThread is to switch to other threads. The SuspendThread is to wait until a call of resume Thread. The WaitForSingleObject is to wait when a particular thread completes its work. The WaitForMultipleObject is used for multiple events. These functions wait for following situations - Change notification, Console input, Event, Job, Mutex ,Process, Semaphore, Thread and Waitable timer.

Benefits of Threads

The multithreaded application uses CPU 100% effectively. When we create a process, it will take more memory space. The multithreaded application shares the same process memory space. Every thread contains stack. So, the thread takes up less memory usage compared to a Process. The process may or may not contain more threads. If you run two or more threads in a process, all the threads share the process address space.

References

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Architect
India India
Selvam has worked on several technologies like Java, Python, Big data, VC++, MFC, Windows API and Weblogic server. He takes a lot of interest in reading technical articles and enjoys writing them too. He has been awarded as a Microsoft Community Star in 2004, MVP in 2005-06, SCJP 5.0 in 2009, Microsoft Community Contributor(MCC) 2011.

Big Data
o Google Professional Data Engineer 2021
o Confluent Certified Developer for Apache Kafka 2020
o Datastax Apache Cassandra 3.x Developer Associate Certification 2020
✓ Cloud
o Google Professional Cloud Architect 2021
o Microsoft Certified: Azure Solutions Architect Expert 2020
o AWS Certified Solutions Architect - Associate 2020
✓ Oracle Certified Master, Java EE 6 Enterprise Architect (OCMEA) 2018

Github : https://github.com/selvamselvam
Web site: http://www.careerdrill.com
Linkedin: https://www.linkedin.com/in/selvamselvam/

Comments and Discussions

 
GeneralRe: very useful article - passing multiple arguments to member function Pin
Selvam R9-Sep-09 17:32
professionalSelvam R9-Sep-09 17:32 
Generalvery good article Pin
Maryam Kasravi23-May-06 21:14
Maryam Kasravi23-May-06 21:14 
GeneralThread Invocation Pin
g_sandipan25-Oct-05 18:55
g_sandipan25-Oct-05 18:55 
Generalunprotected ob object Pin
curiousharry3-Sep-05 8:09
curiousharry3-Sep-05 8:09 
GeneralRe: unprotected ob object Pin
curiousharry3-Sep-05 8:56
curiousharry3-Sep-05 8:56 
Generalunprotected ob object Pin
curiousharry3-Sep-05 8:07
curiousharry3-Sep-05 8:07 
GeneralVery Nice Article Pin
pyrokar2-Apr-05 8:28
pyrokar2-Apr-05 8:28 
GeneralSeveral problems with this article PinPopular
Rolf Schaeuble1-Dec-03 0:02
Rolf Schaeuble1-Dec-03 0:02 
Your article contains several errors/problems:

- In the paragraph 'MFC Multithreaded', you show how to start a thread. But you forgot to show how to wait for it to exit (which you did for the _beginthread() example).
When you start a thread just by calling AfxBeginThread() like your sample shows it, the thread will delete its CWinThread instance automatically when it terminates. Because of this, you cannot safely touch the CWinThread object in the main thread, leaving you with no way to check whether the thread is still running or not.
To correct this behaviour, do the following:
CWinThread* pThread = AfxBeginThread(ThreadFunction, pData, THREAD_PRIORITY_NORMAL, 0, CREATE_SUSPENDED);
pThread->m_bAutoDelete = FALSE;
pThread->ResumeThread();
The CREATE_SUSPENDED flag means that the thread will be created, but it will not immediately start running.
Setting the CWinThreads m_bAutoDelete member to false means that when the thread terminates, it will not delete the CWinThread object. As a result of this, you can use the CWinThread in the main thread since you can rely on it to not go away while you're touching it.
Since the thread was created in suspended state, you have to resume it, so that it actually runs.

Now, later in your application, you can wait for your thread like this:
WaitForSingleObject(pThread->m_hThread, INFINITE);
Then you can delete the CWinThread instance (remember: it doesn't delete itself anymore).

The reason that I mention this is this:
When you just start a thread, and never care about waiting for its termination, you have no control over the threads state. For example: If your application is shutting down, you should make sure that all your spawned threads have finished their work and terminated properly. The way to do this is to signal them to terminate themselves (in any way you like, e.g. with a event), and then wait for them to terminate (WaitForSingleObject on their thread handle).

- In the paragraph 'Win32 Multithread', you write that a thread can terminate itself with TerminateThread(). This is not what this function is intended for. Its purpose is to terminated another thread.
However, terminating another thread with TerminateThread() is generally a very bad idea. As is documented in MSDN Library, the usage of this function can lead to unpredicted behaviour (e.g. deadlocks in your application), and it doesn't free the thread's stack. It shouldn't be used at all. The correct way of terminating another thread is to signal it (e.g. through an event) that it should terminate itself; then wait for it to terminate. This is the way to go if you want your application to behave predictable.


Additionally, I would recommed to everyone who wants to learn about multithreading to read more than one article. Most articles that I've read are missing some important points; so by reading several of them, you should get the whole picture. This article, for example, doesn't mention the most important aspect of multithreading: synchronization. Additionally, reading different articles provides you with different techniques and approaches.
Especially in a complicated field like multithreading, the more you know, the better it is.

GeneralRe: Several problems with this article Pin
Selvam R1-Dec-03 7:23
professionalSelvam R1-Dec-03 7:23 
GeneralRe: Several problems with this article Pin
Rolf Schaeuble1-Dec-03 9:45
Rolf Schaeuble1-Dec-03 9:45 
GeneralRe: Several problems with this article Pin
Selvam R1-Dec-03 12:09
professionalSelvam R1-Dec-03 12:09 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.