Share via


C Run-Time Library Functions for Thread Control

OverviewHow Do ISample

All Win32 programs have at least one thread. Any thread can create additional threads. A thread can complete its work quickly and then terminate, or it can stay active for the life of the program.

The LIBCMT and MSVCRT C run-time libraries provide two functions for thread creation and termination: _beginthread and _endthread.

The _beginthread function creates a new thread and returns a thread identifier if the operation is successful. The thread terminates automatically if it completes execution, or it can terminate itself with a call to _endthread.

! Warning   If you are going to call C run-time routines from a program built with LIBCMT.LIB, you must start your threads with the *_*beginthread function. Do not use the Win32 functions ExitThread and CreateThread. Using SuspendThread can lead to a deadlock when more than one thread is blocked waiting for the suspended thread to complete its access to a C run-time data structure.

The _beginthread Function

The _beginthread function creates a new thread. A thread shares the code and data segments of a process with other threads in the process, but has its own unique register values, stack space, and current instruction address. The system gives CPU time to each thread, so that all threads in a process can execute concurrently.

The _beginthread function is similar to the function in the Win32 API but has these differences:

  • The _beginthread function lets you pass multiple arguments to the thread.

  • The _beginthread function initializes certain C run-time library variables. This is important only if you use the C run-time library in your threads.

  • CreateThread provides control over security attributes. You can use this function to start a thread in a suspended state.

The _beginthread function returns a handle to the new thread if successful or  –1 if there was an error.

The _endthread Function

The _endthread function terminates a thread created by _beginthread. Threads terminate automatically when they finish. The _endthread function is useful for conditional termination from within a thread. A thread dedicated to communications processing, for example, can quit if it is unable to get control of the communications port.