Windows Programming/Multitasking
From Wikibooks, the open-content textbooks collection
This page of the Windows Programming book is a stub. You can help by expanding it.
Current versions of Windows are multitasking operating systems. In this chapter, we will discuss some of the tools and API functions that are involved in multitasking, threading, and synchronization for use in Windows.
Contents |
[edit] Processes and Threads
First, let's explain a little bit of terminology. A process is a single program, with a single entry point, and a single exit point. A Thread, on the other hand is only a part of a process. A process has at least 1 thread, and some processes have more than 1 thread. Threads and processes, when created, run automatically, and are alloted time slices of execution time by the scheduler in a round-robin fashion. The operating system may activate and deactivate any thread or process at any time. For this reason, we will need to control access to program resources such as global memory and output devices.
If the volatility of threads is disconcerting, Windows also provides an execution object known as a fiber that only runs when activated by the parent thread.
If more than one process are working together, the resulting grouping is known as a job. Jobs can also be managed by Windows.
[edit] Managing Processes
- CreateProcess, etc
[edit] Creating Threads
- CreateThread
- beginthread
[edit] Passing Parameters
[edit] Thread Local Storage (TLS)
A single process can (usually) spawn 2000 threads. This is because the default stack size allocated by the linker is 1MB per thread. 1MB x 2000 is around 2GB which is the maximum a user-process can access. Following is a sample code which spawn many threads till a limit is reached:
// Threads.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <process.h>
#include <conio.h>
#include <windows.h>
unsigned int __stdcall myThread (LPVOID params) {
printf ("Inside thread");
Sleep (INFINITE);
return 0;
}
int _tmain(int argc, _TCHAR* argv[])
{
int i = 0;
unsigned int dwThreadId = 0;
while (true) {
HANDLE h = (HANDLE) _beginthreadex (NULL, 0, myThread, NULL, 0, &dwThreadId);
if (h == NULL) break;
++i;
}
printf ("\n\nI spawned %d threads", i);
Sleep (10000);
return 0;
}