Exception when creating a Thread with Windows

stef s1234567 at gmail.Com
Sat Jul 5 10:39:13 UTC 2025


Hello,

I'm totally new using D. I'm trying to create a thread using this 
code:


```d
import std.stdio;
import core.thread;
import core.time;

import std.format;
import core.stdc.stdio;

void myThread()
{
	for (int i = 0; i < 5; i++)
	{
		writefln("Message from secondary thread : %d", i);
		Thread.sleep(500.msecs);
	}
}

import core.sys.windows.windows;
import core.sys.windows.winbase;

extern (Windows)
int WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
	LPSTR lpCmdLine, int nCmdShow)
{
	MessageBoxA(null, "Application started", "Info", MB_OK | 
MB_ICONINFORMATION);

	if (AllocConsole())
	{
		SetConsoleTitleA("Threads Test Application");
		freopen("conout$", "w", core.stdc.stdio.stdout);
		freopen("conout$", "w", core.stdc.stdio.stderr);
	}

	writeln("=== Threads Test Application ===");

	Thread thread = null;
	try
	{
		thread = new Thread(&myThread);
		thread.start();
	}
	catch (Exception e)
	{
		writeln("Error starting thread: ", e.msg);
		MessageBoxA(null, "Error starting thread", "Error", MB_OK | 
MB_ICONERROR);
		return 1;
	}

	MessageBoxA(null, "Thread started", "Info", MB_OK | 
MB_ICONINFORMATION);

	for (int i = 0; i < 10; i++)
	{
		writefln("Message from main thread : %d", i);
		Thread.sleep(dur!"msecs"(1000));
	}

	thread.join();

	writeln("=== End of Application ===");
	return 0;
}

```

I'm testing this program using Visual Studio Code. I 
systematically have an exception (not trapped, I don't know why 
by the catch) when it's calling thread.start(). I can see it only 
with the debugger.

The exception is:

W32/0xC0000005
Unhandled exception at 0x00007FFB5F379463 (ntdll.dll) in 
threads-debug.exe: 0xC0000005: Access violation writing location 
0x0000000000000024.

Is it a mistake or a bug ?

A similar code is working using the console mode.

Regards,
stef




More information about the Digitalmars-d-learn mailing list