Archived

This topic is now archived and is closed to further replies.

Dwiel

Threads - who what when where why?

Recommended Posts

I am a little new to C++ programming, and I have heard a lot about threads, and how usful they are in some situations. Would anyone be kind enough to explain to me what they are, what they accomplish, how you use them etc.... Thanx alot Ahead! Tazzel3D ~ Zach

Share this post


Link to post
Share on other sites
Threads are flows of program exectution..

For example.. My Server program.

If I where to call "cin" exectution would stop.. If I was to call "recvfrom" (The function I use to get net messages. If you don''t know) the execution would stop.

So what happens if I want to recv AND get input at the same time? Well.. Without threads this would be impossible.

hID = CreateThread(...); // Use it to Create my new thread from GetMessages();

cin >> b; // Get Command

void GetMessages()
{
recvfrom(...);
}

Now I have 2 threads.. one is sitting on "cin" the other is sitting on recvfrom. Get it? Just in case not let me clarify..

Use CreateThread(); or _beginthread(); to create a seperate line of execution. So basicly it''s like running 2 programs at the same time.

One catch.. It''s usally slow.



------------------------------------------------------------
I wrote the best video game ever, then I woke up...

Grandus.Com

Share this post


Link to post
Share on other sites
Threading basically means parallel execution. This means the the program is doing two things at the same time. This is sort of misleading though. Unless you have multiple processors the threading is emulated. It does this by giving each execution flow a small "chunk" of CPU time and switches between all the threads. So it appears that it is doing do things at once but is infact interleaving the seperate processes.

However, multithreading programming is very hard to do right. With multiple things sharing memory the possibilites for errors are endless . You also have to worry about things such as deadlock.


I''ve most seen threading in network applications. For example when a client connects to the server the server can start a new thread to handle that client.



-------
Andrew
"Power comes in response to a need not a desire."
gdNgine Development

Share this post


Link to post
Share on other sites