views:

108

answers:

4

What are the rules regarding spawning new threads within other running threads? I have a C# app that handles two basic threads in the background. I recently introduced some heavy duty IO stuff, and I was thinking of setting them off inside threads. Are threads nested within themselves cool?

+1  A: 

Threads don't nest within each other - threads belong to a process. So if you have threads A & B, and then they each create C & D, C & D don't belong to A & B - they belong to your process.

So yes, creating additional threads from background threads is acceptable.

Michael
A: 

The best solution I've found to the generic multithreading problem has always been to have a pool of always-running "worker threads" for which you create jobs that are pushed onto a queue. The next available worker thread will pop the next job off the queue and start churning away on it. This gives you the multithreaded capability one would hope for and the encapsulation required to keep one's head from exploding.

fbrereto
Sounds sensible, and optimal. I'll consider this,thanks
Olaseni
A: 

Threads aren't modelled as a hierarchy for the majority of their processing; the concept of "nesting" simply doesn't exist.

A thread executes in parallel to all other threads, regardless of which thread created it. The only things which matter in the creation of a thread is whether it is a background thread or a foreground thread and the priority of the thread:

  • Priority determines how many slices of time the thread is given when competing with other threads for resources. Higher priority means more slices.

  • Foreground threads keep a process alive until their work is completed. For background threads, when all foreground threads complete execution in a process, the process ends and the background threads are terminated, regardless of their work completed.

Programming Hero
Well, in most systems there is a concept of parent and child thread. This is usually relevant because only the parent thread will get a handle for the newly launched thread, e.g. for waiting for it to terminate. So there is a kind of hierarchy...
sleske
He said C# so I presume Windows, there is no such concept of a parent/child thread.
Michael
+1  A: 

If the parent thread is waiting on child thread, this presents a new synchronization requirement that might cause deadlock.

example: (T stands for thread, R for shared resource)

  • T1 locks R1
  • T1 starts T2
  • T3 locks R2
  • T2 waits on R2
  • T1 waits on T2
  • T3 waits on R1