[Mono-list] Threading

Piers Haken piersh@friskit.com
Mon, 13 May 2002 15:24:15 -0700


On Win32 a process terminates normally when ALL of its threads have
exited. It does not necessarily terminate when the 'main' thread
terminates.

However, Microsoft's C runtime makes an explicit call to ExitProcess
after the return from main(). From crt\src\crt0.c:

	int mainret;
	...
	mainret = main (__argc, __argv, _environ);
	exit (mainret);

When CreateThread returns success the thread is guaranteed to have been
created (thus preventing the process from terminating) but it may not
have received a timeslice yet.

The following C program demonstrates this:

#include <windows.h>

DWORD WINAPI ThreadProc (LPVOID *lpv)
{
	Sleep (10 * 1000);
	return 0;
}

int mymain ()
{
	DWORD dwThreadId;
	CreateThread (NULL, 0, ThreadProc, NULL, 0, &dwThreadId);
	return 0;
}

C:\> cl thread.c /link /nodefaultlib /subsytem:console /entry:mymain
kernel32.lib

NOTE: the /link flags cause the process entry to be at the mymain
function thus bypassing the C runtime. The /subsystem switch causes the
shell (CMD.EXE) to run the process in the forground (ie, in unix terms,
without a trailing '&')

HTH.
Piers.