Thread
A thread is the basic unit of CPU utilization; it consists of a thread ID, a program counter, a register set, and a stack. Each thread belongs to exactly one process and shares with other threads of the same process its code sections, data sections, and operating system resources, such as open files and signals. A process can have one or more threads.
Overview
Threads provide a way to improve application responsiveness by allowing a program to perform multiple tasks concurrently. For example, a word processing application might use one thread to display text on the screen, another thread to spell-check the document, and a third thread to save the document to disk. This allows the user to continue typing while other operations are being performed in the background.
Key Concepts
- Thread Creation: Threads can be created using functions like
CreateThread
. - Thread Scheduling: The operating system scheduler determines which thread runs on the CPU at any given time.
- Thread Synchronization: Mechanisms like mutexes, semaphores, and critical sections are used to control access to shared resources.
- Thread Communication: Threads can communicate with each other through shared memory, message queues, or other inter-thread communication primitives.
- Thread Termination: Threads can terminate themselves or be terminated by the operating system or another thread.
Related Functions
Function | Description |
---|---|
CreateThread |
Creates a new thread in the calling process. |
ExitThread |
Causes the calling thread to exit. |
WaitForSingleObject |
Waits until the specified object is in the signaled state or the time-out interval elapses. Can be used to wait for thread completion. |
Sleep |
Suspends the current thread for a specified interval. |
GetCurrentThreadId |
Retrieves the identifier of the current thread. |
SetThreadPriority |
Sets the priority of the specified thread. |
Example: Creating a Simple Thread
#include <windows.h>
#include <iostream>
// Thread function
DWORD WINAPI MyThreadFunction(LPVOID lpParam) {
int threadId = *(int*)lpParam;
std::cout << "Hello from thread " << threadId << "!" << std::endl;
// Perform some work here...
Sleep(2000); // Simulate work
std::cout << "Thread " << threadId << " finished." << std::endl;
return 0; // Thread exits successfully
}
int main() {
DWORD threadID;
int id1 = 1;
HANDLE hThread1 = CreateThread(
NULL, // default security attributes
0, // default stack size
MyThreadFunction, // function pointer
&id1, // argument to thread function
0, // default creation flags
&threadID); // receives thread identifier
if (hThread1 == NULL) {
std::cerr << "Failed to create thread. Error: " << GetLastError() << std::endl;
return 1;
}
std::cout << "Main thread: Created thread with ID " << threadID << std::endl;
// Wait for the thread to finish
WaitForSingleObject(hThread1, INFINITE);
// Close the thread handle
CloseHandle(hThread1);
std::cout << "Main thread finished." << std::endl;
return 0;
}