C# threading... dont know where to begin

Started by
3 comments, last by SimonForsman 17 years, 1 month ago
So ive been searching around for information about threading. I understand that are for running multiple processes at once (pretty sure). I know how to create them, but i dont know how to use them and how they opperate. Lets pretend i created (which i didnt, just using it as example) a very small arena type map. Inside is me (the player) and 3 AI controlled mobs. Does each mob use its own thread? I decide to cast a Fireball at one of the mobs. Does that single Fireball graphic run on its own thread, to get from me to the targeted mob? Im really confused about this thread stuff so sorry if this seems... different. If anyone can give me a very good tutorial and/or sample code that would be awsome.. Im having a lot of trouble getting info about the "threading" stuff. Any other info about threads would be greatly appriciated too.
Advertisement
No, that's not how you should do it. You should have all the fireballs and players and logic stuff in the same thread. You should probably also use that one thread for your graphics and AI.

The reason is that when you have multiple threads accessing the same data, there's all sorts of new problems that can come up. What if two threads want to write to something at the same time? You may lose one of the changes or run into even more serious problems.

However, if your code is running on a multicore CPU, you can get large benefits from using two or four threads that split the work evenly. It may not be worth the effort for most indie projects, though.

Here's a few things that can do well with their own threads:

networking - it doesn't use much CPU, but it may send or recieve packets at any time

sound - it doesn't need to share very much data with the rest of the game

loading resources - you can have a thread that loads areas the player may go to next while the player is playing in the main thread. That can really reduce load times. It can also be used to create huge, seamless outdoor areas, loading only the areas around the player without any load screens. Again, this may be a bit heavy duty for small projects.

You don't need threads at all for simple games; you can do most stuff without them.

If you still want to learn about threading, google 'C# threading tutorial' and look at the first page of links.
Threads are generally not beginner (or intermediate) material. They make both debugging and proper program design oodles harder. They're not for running multiple processes at once, they're a mechanism for allotting processor time to different bits of a single process.

Each mob would not use its own thread. The AI might have its own thread depending on how much information it would need to share with the rest of the app, and other factors into whether that approach would be better than placing AI routines into the normal single threaded gameloop. Most (all?) rendering APIs restrict calls to a single thread, so the animation would likely need to run in whichever is your graphics thread.

There are not too many good threading tutorials. The problem comes that most APIs provide about a half dozen threading specific objects/functions (System.Threading provides only a few main ones: Thread, ThreadPool, Monitor, Interlocked). Those though (and running in a threaded context) effects pretty much every other object you'll ever use. So it's a little difficult to describe something sufficiently when the scope of what it effects is... everything.

Here's something quick:
using System;using System.Collections.Generic;using System.Text;using System.Threading;namespace Csharp_threadtest1 {    class foo { }    class Program {        static foo x=new foo();        static void Moo(string str) {            lock (x) {                            Console.WriteLine("{0}", str);            }        }        static void Main(string[] args) {            Thread moo1, moo2;            moo1=new Thread(delegate (){int x; for (x=0;x<5;++x){Moo("1!");}});            moo2=new Thread(delegate (){int x; for (x=0;x<2;++x){Moo("2.");}});            moo1.Start();            moo2.Start();        }    }}


Which on one run produces:
1!2.2.1!1!1!1!


As you can see, the threads run concurrently. Well, on my machine they run concurrently, maybe; if the OS decides to run them concurrently... On a single processor, single core machine they won't run concurrently but they'll still act like they are. And within the lock{} they won't run concurrently (though one can be in the lock and the other incrementing its loop). And if I run the program again, I might get different results.

So that's kinda how they operate. To use them... eh, just don't use them until you've a really firm grasp on how things work without them, program design and your debugger. (and you know enough to know when they'll save you time and effort)
Oh i see, ive always thaught each mob runs on its own thread. How would i go about making each mob move at the same time? Well maybe not the same time, but make it look like its at the same time? Such as a real-time rpg? And the same with spells, such as a fireball casting?
Quote:Original post by javasirc
Oh i see, ive always thaught each mob runs on its own thread. How would i go about making each mob move at the same time? Well maybe not the same time, but make it look like its at the same time? Such as a real-time rpg? And the same with spells, such as a fireball casting?


thats easy:

basically you have your gameloop

pseudo code
while(!done) {    dt = timeSinceLastFrame();    updateAllObjects(dt);    drawAllObjects();    swapBuffers(); //copy the backbuffer to the front so that everything you did shows up on the screen}


thats pretty much it. (ofcourse there is alot more in a real game).
[size="1"]I don't suffer from insanity, I'm enjoying every minute of it.
The voices in my head may not be real, but they have some good ideas!

This topic is closed to new replies.

Advertisement