Quick Threading Tutorial - C++
Programming
|
Threading In C++, By Otoom
Hello, I will show you how to thread in C++.
First you need to create the thread, so if we place this into our editor...
CODE:
|
Copy / Restore :: Remove Scroll Bars
|
DWORD WINAPI Threadname (LPVOID lPData) { } int main() { }
Select what you want to copy and in doing so you will keep the formatting when pasting it.
|
|
Okay, and that is the basic layout.
Now we have declared the thread, of course change Threadname to whatever you would like to call it.
What we can now do is, call on that thread within the main.
So if we add a little bit of code...
CODE:
|
Copy / Restore :: Remove Scroll Bars
|
DWORD WINAPI Threadname (LPVOID lpData) { } int main() { HANDLE Threadname = CreateThread(NULL,0, Threadname, NULL,0,0); }
Select what you want to copy and in doing so you will keep the formatting when pasting it.
|
|
Okay, so, What have we done here?
What we have now done is call upon the thread we declared. Using a handle.
But after all this, i bet you think what can threads even do.
Okay well. Threads let you run something else while running main.
It is like a background running program but within the same application.
For example.
We can show the lyrics of a song, while making the beeps of it.
I hope you get that.
So... Now.
CODE:
|
Copy / Restore :: Remove Scroll Bars
|
DWORD WINAPI Beeps (LPVOID lpData) { while(1) { cout<<"\a"; } } int main() { HANDLE Beeps = CreateThread(NULL, 0, Beeps, NULL, 0,0); cout<<"You can hear the beeps...\n"; cout<<"While looking at this text...\n"; }
Select what you want to copy and in doing so you will keep the formatting when pasting it.
|
|
Just on a side note, the lpData is not needed.
I just included it as thats the way i learned it.
OtoomPlease login to rate coding articles.
Click here to register a free account with us. |
|
Comments
|
Please login to post comments. |
|
Yeah i wrote this the day i learn about threading in C++. And as you see, only in windows.
And now, i don't code in C++ so i am not going to learn about anymore of this,
|
|
Hi,
i'm missing some information. First of all this is windows only, it would be great to supply alternatives like pthread. Secondly what do all the parameters to CreateThread() mean? And why do you say that the void-pointer is not needed?
If i want to pass arguments to my thread-function i can sure use this pointer.
Also it would be great if you would say sth about problems that arise when you're in a multithreaded environment like race-conditions and other synchronization-problems.
Beside that the article is ok, but it won't get anybody very far. But as a starting point it's suitable i guess.
cheers
|
|
|
 |
Ant (17) United Kingdom, West Midlands |
|
otoom has 8 fans
become a fan |
|
 |
|
 |
|