Multi Threading using Visual Studio

Alright so I've been reading up on threads and how to code them and I am stumped. I have been given an aissgnment to create a main thread which then creates two child threads. The program must show the threads were created and when they are terminated. Here is my program so far:

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
#include	<windows.h>
#include	<iostream>
#include	<process.h>
#include	<stdlib.h>

using namespace std;

int child;
int id=1;
bool f1Run=true;
bool f11Run=true;
bool f12Run=true;

unsigned __stdcall f2(void* a) {
	child=*(int*)a;
	cout << "Child Thread: " <<  *(int*)a<<" Created "<<endl;
	if(*(int*)a==11){f11Run=false;}
	if(*(int*)a==12){f12Run=false;}
	return 0;
}


unsigned __stdcall f1(void* a) {
	cout<<"Thread "<<*(int*)a<<endl;
	int id1=11;
	HANDLE t2 = (HANDLE) _beginthreadex(NULL, 0,  f2,  &id1, 0, 0);
	//Sleep(10);
	int id2=12;
	HANDLE t3 = (HANDLE) _beginthreadex(NULL, 0,  f2,  &id2, 0, 0);
	Sleep(100);
	while(f11Run||f12Run){}
	cout<<"Thread Terminated "<<child<<endl;
	f1Run=false;
	return 0;
}


void main()
{

	HANDLE t1 = (HANDLE) _beginthreadex(NULL, 0,  f1,  &id, 0, 0);
	while(f1Run){}
	cout<<"Main Thread Terminated"<<endl;
	getchar();
	
}



When I run the program, it sghows that a main thread and 2 children thread have been created however it only shows the second child thread and the main thread terminate, not the first one. Does anyone see a problem with my code? Any input would be greatly appreciated. Thanks.
ok... both child threads are setting child and you wait for them both to end, then cout the one that set child last... do you see the problem?

-- edit... plus, it should be int main() and you are setting all these HANDLE vars, but not using them, is that for later? plus you need #include <cstdio> for getchar();
Last edited on
The thread that's running when the app starts is the main thread.

You don't want all those Run variables and while loops. You need to synchronise the threads with WaitForSingleObject.
Topic archived. No new replies allowed.