Microsoft Computing: Threading Under Windows

  • Smaller Small Medium Big Bigger
  • Default Helvetica Segoe Georgia Times

You use threads all the time; you'd miss them if they were gone. Whenever you print a document in Microsoft Word or reformat a spreadsheet in Excel, you're using threads. In these applications, threads are being used to insulate you from long-running tasks that can be done in the background.

What Is a Thread?

A thread, a.k.a. a lightweight process, is a portion of a program that runs semi-independently of the rest of the program. You might think of a thread this way: Suppose you have an ordinary Windows program that calls a function. But this is no ordinary function. This function starts running as you would expect, but the part of the program that called the function does not wait for the function to complete. The program resumes execution immediately, and now there are two sets of instructions running at the same time over the same process space.

Cute trick, you say, but here's the best part: Each set of instructions that is running (threads) can access the same program elements that the other can--things like open files, variables, pointers, communication resources, etc. This can be a handy technique, indeed.

Here's an iSeries analogy: Suppose you have an iSeries CL program (Program A) that submits a job (Program B). The submitted job (B) begins operation, and the program that submitted it (A) keeps on going without waiting for B to finish. Now, there are two jobs running on your behalf, but they are independent of each other and can't share resources.

How Threading Works

Sometimes, within a single application, you need to have two threads of execution running at the same time. As an example, consider a chat room application. Typically, a chat room client will have two windows: one where messages are keyed in and another where messages keyed by others are displayed. The two concurrent processes (accepting keyboard input and displaying messages sent from others) must run as independent threads of execution within a single process. Otherwise, either messages must wait to be displayed until keyboard input is complete or the other way around.

So when the chat room program is started, it starts a second thread of execution (called spawning a thread) that has the singular task of listening for incoming messages on a communications link and displaying them on the applications screen. The original program (also a thread of execution) has the counterpart task: accepting user keystrokes and writing them to the same communications link.

Each thread of execution within a single process space has its own program counters for holding the next instruction, its own registers for holding current working variables, and its own stack for holding execution addresses and other data.

Avoiding Collisions in Concurrent Threads

Within a single application that uses threads of execution, there exists the potential for problems caused by unfortunate timing of events. Take the chat room, for example. Suppose the reading thread is in the middle of receiving a long transmission when the writing thread decides to send its data. Since both threads are sharing the same resource (the open communications port), there needs to be some way of keeping each from annoying the other during critical regions of operations. Such a chunk of code that is protected through a critical region is said to be thread-safe.

There are two commonly available system objects that control resource allocation during critical regions of processing to make a thread safe: the mutex and the semaphore.

A mutex (short for mutually exclusive) is essentially a flag bit that a given thread can set to a locked position at the beginning of a critical section of processing and then unlock at the end. Other threads must check the mutex, and if it's locked, they must wait.

A semaphore is like a mutex in that it's used to control access to shared resources, but it's a bit more complex and capable. A semaphore contains a counter of available resources and is used to synchronize multiple threads within a single independent process or multiple independent processes.

Thread Programming in Windows

Windows has a number of APIs available to programmers for writing threading applications, including the following (shown in usual order of use):

  • HeapAlloc allocates space on the heap for thread parameters.
  • CreateThread spawns a new thread.
  • WaitForMultipleObjects makes the parent thread wait for spawned threads to finish.
  • HeapFree returns allocated heap space to the operating system.
  • CloseHandle removes references to spawned threads from the parent.

The following simplified C/C++ code example, taken from Microsoft's Developer Network, illustrates an implementation of the basics of threading. The code may be compiled and run in Microsoft Visual Studio.

The example code creates three threads. Each thread (called ThreadProc) prints a short message on the console to identify itself, cleans the memory used for the passed parameter from the heap, and then terminates. The parent function (main) will use the WaitForMultipleObjects API call to ensure that all threads have finished execution before main itself terminates. Note that all child threads of execution will cease to exist if the parent thread is terminated.


#define MAX_THREADS 3
#define BUF_SIZE 255

// Structure used as a parameter to the spawned thread...
typedef struct _MyData {
    int val1;
    int val2;

// This is the spawned thread...
DWORD WINAPI ThreadProc( LPVOID lpParam ) 

    // Pointer to a struct for the incoming parameters...
    PMYDATA pData;

    // Cast the parameter to the correct data type.
    pData = (PMYDATA)lpParam;

    // Print a message to identify the thread...
    printf("This is thread number %d ", pData->val1);

    // Free up allocated heap memory...
    HeapFree(GetProcessHeap(), 0, pData);

    return 0; 

// Program execution starts here in main...
void main()
    PMYDATA pData;
    DWORD dwThreadId[MAX_THREADS];
    int i;

    // Create MAX_THREADS worker threads.
    for( i=0; i
        // Allocate memory for thread data.
        pData = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY,

        if( pData == NULL )

        // Generate some unique data for each thread...
        pData->val1 = i;
        pData->val2 = i+100;

        // Create the spawned thread...
        hThread[i] = CreateThread( 
            NULL,              // default security attributes
            0,                 // use default stack size  
            ThreadProc,        // thread function 
            pData,             // argument to thread function 
            0,                 // use default creation flags 
            &dwThreadId[i]);   // returns the thread identifier 
        // Check the return value for success. 
        if (hThread[i] == NULL) 

    // Wait until all threads have terminated.
    WaitForMultipleObjects(MAX_THREADS, hThread, TRUE, INFINITE);

    // Close all thread handles upon completion.
    for(i=0; i

Notice the use of "handles" as is common in Windows programming. A handle is essentially a number used to keep track of a Windows object. When a handle is returned by a Windows API, the system has mapped the value to an internal table where all of the details of the object in question are kept. The programmer need only pass the handle reference to the operating system for many subsequent services (the CloseHandle API call, for example).

Threading is a standard means of producing more-capable applications and is available in most operating systems. The concepts and general flow of events are basically the same with some minor exceptions. In Linux, for example, the system call to the kernel that creates a new thread is pthread_create.

It might be time well-spent to dig into thread programming. With a little experimentation, coding to the threading model can become a big help in producing more-capable, more-convenient applications.

Chris Peters has 26 years of experience in the IBM midrange and PC platforms. Chris is president of Evergreen Interactive Systems, a software development firm and creators of the iSeries Report Downloader. Chris is the author of The OS/400 and Microsoft Office 2000 Integration Handbook, The AS/400 TCP/IP Handbook, AS/400 Client/Server Programming with Visual Basic, and Peer Networking on the AS/400 (MC Press). He is also a nationally recognized seminar instructor. Chris can be reached at This email address is being protected from spambots. You need JavaScript enabled to view it..