multiple threads

Can someone give me an example of how to create and use threads in C++?

Just a very simple example would suffice...

I haven't really played with threads to much. But heres a simple example how to create one and pass a number into it to be displayed.

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

// Function to create a thread.
DWORD WINAPI ThreadProc(LPVOID lpParam)
{
	while(true)
	{
		int* number = (int*)lpParam; 
		std::cout << "In Thread - Value passed in: " << *number << std::endl;
	}

	return 0;
}

int main()
{
	int* num = new int;
	*num = 10;

	DWORD ThreadID;
	// Create the thread and pass the "num" into ThreadProc()
	CreateThread( NULL, 0, (LPTHREAD_START_ROUTINE)ThreadProc, num, 0, &ThreadID);

	while(true)
	{
		std::cout << "In Main" << std::endl;
	}

	return 0;
}
Last edited on
FYI, if you want a cross platform version, I would check out boost. Linux also has it's own threading lib, I think it's called pthread or something, if you are building for just Linux.
Thanks mate!
Hope it makes sense and it's what you needed :)
Topic archived. No new replies allowed.