CreateThread problem

I have quite a big MFC application at my disposal which I want to break down to the stuff I actually need. However I am just using Standard Windows Libraries.
Now I am little stuck with the createThread function, it doesn't seem to act the same way as in the MFC app. In my thread function there are some other functions, which don't seem to be called.
Therefore I tried to make a minimum working example in order to understand the process better. So if I run this code the output is "01". I expected it to be "11" though. It looks like it calls the first "cout << m.Testvar;" first and then it jumps to the thread function. Why does it behave that way?

I am still a bloody beginner in terms of C++ so there is a chance I get the terminology mixed up and I might have given too less Information. So please forgive me if that is the case. Anyway thanks in advance.

P.S. In the MFC app it jumps to the startButton (you guessed it) via a button. Everything works fine there.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <windows.h>
#include <iostream>
using namespace std;

class MyClass
{

public:

	static DWORD CALLBACK ThreadFunction(LPVOID lpParameter);
	HANDLE ThreadID = INVALID_HANDLE_VALUE;

	void startButton();

	int Testvar = 0;
};


void main()
{
	// Create an instance of the class CEthernetScannerDLLTestStatischDlg in order to call the member function
	MyClass m;

	m.startButton();
	
	cout << m.Testvar;
	cout << m.Testvar;
	cin.get();

}

void MyClass::startButton()
{

	DWORD lpThreadId;
	ThreadID = CreateThread(NULL,
		NULL,
		(LPTHREAD_START_ROUTINE)ThreadFunction,
		(LPVOID)this, //Pointer to this Class. to access the Class-Variables from the Thread
		0,
		&lpThreadId);
	
}

DWORD WINAPI MyClass::ThreadFunction(LPVOID lpParameter)
{

	MyClass *pDlg = (MyClass *)lpParameter;

	pDlg->Testvar++;
	return 0;
}
A newly created thread doesn't necessarily start running right away. The current thread will probably continue for a while. I'm surprised it's not printing 00 (or possibly 11). 01 seems like the least likely outcome! Then again, it may be the fact that the current thread requested output that caused the OS to switch threads at that point.
Last edited on
Don't use CreateThread, use _beginthreadex.

Pay attention to synchronization betweeen threads that access shared data, as mentioned above.
Topic archived. No new replies allowed.