Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to wrap my head around threads

I am trying to wrap my head around how threading works, and I believe I might have overcomplicated it.

Original Understanding:

Previous I thought threads were limited to a single class and its sub classes, no class can be shared across threads, and the communication between threads made it real hard for me to understand.

New understanding:

But the more I read about it, it instead seems like threads are just running at a random point in the same code. You can restrict it to certain areas but in theory the same code could run multiple times in each of the threads.

To put it another way, if you see the code as a road system with turns and connections, those are the flow a program can make, the main thread just runs through this. If a new thread is spawned all you do is saying where it should start from, and the code goes from there, can use same classes and commands, so if you structure your code "bad" there is the risk of two pieces of code "crashing", but beside that there is no restrictions on reading from and writing to code, its all part of the same program, just multiple "cars" on the "roads".

You could restrict a thread to stay within a certain area (loop/limited part of code), and only interact at certain places, or you could ignore it and just hope to avoid the "crashes".


With the "New understanding" working with threads it is for me so much easier to wrap my head around, so is it understood correct?

like image 376
Taoh Avatar asked Mar 25 '13 09:03

Taoh


1 Answers

You have pretty much hit it. In general threads are there to do specialized work and won't overlap with each other. If the main thread has to spawn off a sub-thread to do work, the main thread will almost always not also be doing this work.

The areas where they do overlap will need to be "Thread safe" so as not to step on each other's toes; for example multiple worker threads filling up a collection for the main thread. When you're looking up classes on MSDN you'll notice the blurb at the bottom saying whether they have thread safety built in or you'll need to do it yourself through the use of .net's locking, mutexes or semaphores.

like image 100
Nick Avatar answered Oct 11 '22 14:10

Nick