Windows Win32 API: Process and Threads

Reference documentation and concepts for managing processes and threads on Windows.

Processes

A process is an instance of a running program. It is an independent execution environment that has its own memory space, system resources (like file handles), and security context. Each process has at least one thread of execution.

Key Process Concepts

  • Process ID (PID): A unique identifier assigned to each process.
  • Address Space: The virtual memory range allocated to a process.
  • Handles: References to system objects (like files, threads, or processes) that a process can interact with.
  • Environment Block: Contains environment variables for the process.

Threads

A thread is the smallest unit of execution within a process. Multiple threads can exist within a single process, sharing the process's resources (memory space, open files, etc.) but having their own execution context, such as program counter, stack, and registers. This allows for concurrent execution of tasks within a single application.

Key Thread Concepts

  • Thread ID (TID): A unique identifier for each thread.
  • Thread Local Storage (TLS): A mechanism to store data unique to each thread within a process.
  • Stack: Each thread has its own stack for local variables and function calls.

Scheduling

The Windows operating system scheduler is responsible for allocating CPU time to processes and threads. It uses priority-based, preemptive scheduling to ensure that high-priority tasks get CPU resources when needed.

Priorities

Processes and threads are assigned priority levels, ranging from low to real-time. The scheduler dynamically adjusts priorities based on thread activity.

Synchronization

When multiple threads access shared resources, synchronization mechanisms are crucial to prevent race conditions and ensure data integrity. The Win32 API provides several synchronization objects.

Common Synchronization Objects

  • Mutexes (Mutual Exclusion Objects): Allow only one thread to access a shared resource at a time.
  • Semaphores: Control access to a pool of resources by maintaining a count.
  • Events: Used to signal the occurrence of an event between threads.
  • Critical Sections: A lightweight synchronization mechanism for threads within the same process.

Inter-Process Communication (IPC)

IPC mechanisms allow different processes to exchange data and synchronize their operations. While threads within a process share memory, processes generally have separate address spaces.

Common IPC Mechanisms

  • Pipes: Unidirectional or bidirectional communication channels.
  • Memory-Mapped Files: Allow processes to share a region of memory.
  • Sockets: Used for network communication, but can also be used for local IPC.
  • Window Messages: A message-based system for communication between windows and processes.

Key API Functions

CreateProcess BOOL CreateProcess( _In_opt_ LPCSTR lpApplicationName, _Inout_opt_ LPSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCSTR lpCurrentDirectory, _In_ STARTUPINFO *lpStartupInfo, _Out_ PROCESS_INFORMATION *lpProcessInformation );

Creates a new process and its primary thread. The new process runs the specified executable program.

ExitProcess _Noreturn VOID ExitProcess( _In_ UINT uExitCode );

Terminates the calling process and all of its threads.

CreateProcessInternalW BOOL CreateProcessInternalW( _In_opt_ HANDLE hToken, _In_opt_ LPCWSTR lpApplicationName, _Inout_opt_ LPWSTR lpCommandLine, _In_opt_ LPSECURITY_ATTRIBUTES lpProcessAttributes, _In_opt_ LPSECURITY_ATTRIBUTES lpThreadAttributes, _In_ BOOL bInheritHandles, _In_ DWORD dwCreationFlags, _In_opt_ LPVOID lpEnvironment, _In_opt_ LPCWSTR lpCurrentDirectory, _In_ STARTUPINFOW *lpStartupInfo, _Out_ PROCESS_INFORMATION *lpProcessInformation );

An internal version of CreateProcess, typically used by system processes. It allows specifying an access token for the new process.

GetCurrentProcess HANDLE GetCurrentProcess( VOID );

Returns a pseudohandle for the current process. This pseudohandle is valid only for the context of the calling process.

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

Creates a new thread to execute within the virtual address space of the calling process.

ExitThread VOID ExitThread( _In_ DWORD dwExitCode );

Terminates the calling thread and returns a termination code to the calling process.

GetCurrentThread HANDLE GetCurrentThread( VOID );

Returns a pseudohandle for the current thread. This pseudohandle is valid only for the context of the calling thread.

Sleep VOID Sleep( _In_ DWORD dwMilliseconds );

Suspends the current thread for the specified number of milliseconds.

WaitForSingleObject DWORD WaitForSingleObject( _In_ HANDLE hHandle, _In_ DWORD dwMilliseconds );

Waits until the specified object is in the signaled state or the time-out interval elapses.

WaitForMultipleObjects DWORD WaitForMultipleObjects( _In_ DWORD nCount, _In_ const HANDLE *lpHandles, _In_ BOOL bWaitAll, _In_ DWORD dwMilliseconds );

Waits until one or all of the most current nCount objects in the specified array are signaled, or until the time-out interval elapses.

CreateMutex HANDLE CreateMutex( _In_opt_ LPSECURITY_ATTRIBUTES lpMutexAttributes, _In_ BOOL bInitialOwner, _In_opt_ LPCSTR lpName );

Creates or opens a mutex object. Mutexes can be named for inter-process use.

ReleaseMutex BOOL ReleaseMutex( _In_ HANDLE hMutex );

Releases ownership of the specified mutex object. The calling thread must own the mutex.

CreateSemaphore HANDLE CreateSemaphore( _In_opt_ LPSECURITY_ATTRIBUTES lpSemaphoreAttributes, _In_ LONG lInitialCount, _In_ LONG lMaximumCount, _In_opt_ LPCSTR lpName );

Creates a semaphore object. Semaphores maintain a count of available resources.

CreateEvent HANDLE CreateEvent( _In_opt_ LPSECURITY_ATTRIBUTES lpEventAttributes, _In_ BOOL bManualReset, _In_ BOOL bInitialState, _In_opt_ LPCSTR lpName );

Creates an event object. Events can be manual-reset or auto-reset.

SetEvent BOOL SetEvent( _In_ HANDLE hEvent );

Sets the specified event object to the signaled state. Threads waiting for the event are released.

ResetEvent BOOL ResetEvent( _In_ HANDLE hEvent );

Sets the specified event object to the non-signaled state. For manual-reset events.

CreateThreadpoolWork PTP_WORK CreateThreadpoolWork( _In_ PTP_WORK_CALLBACK pwkcb, _In_opt_ PVOID pv, _In_opt_ PTP_CALLBACK_ENVIRON pcbe );

Creates a work object that can be queued to a thread pool.

SubmitThreadpoolWork VOID SubmitThreadpoolWork( _Inout_ PTP_WORK pck, _In_opt_ PVOID pv );

Submits a work item to a thread pool for asynchronous execution.