다음을 통해 공유


Threading deep dive – Day 10

In the previous day we saw what would happen underneath when we create a managed thread and how it maps to native thread. That is what would happen when a managed thread executes a native / managed code.

There are situations where native thread executing the native code would need to execute managed code. For example, we can consider the case of a com component executing managed code. In those cases, when the native thread, for the first time, execute the managed code, the native object [not the managed thread object] would be created and the execution would proceed. Here the managed thread object would never get created unless the managed code refers the executing thread using the API like Thread.CurrentThread

 What are Fibers?

Fibers are like light weight threading objects that can be executed in parallel. Multiple fibers can be executed in a single thread. The advantage over here is that the same thread would be serving multiple fibers and the application can take the responsibility of scheduling the fibers. In case of threads, the scheduling responsibility is with the operating system. If we go with fibers, we can control scheduling of the fibers. On the negative end, Fibers are so far not yet supported in Managed code. Fibers do not support synchronization like threads. Hence the overhead fibers create overweighs the light weightiness it provide. CLR team faced some issues before they release .NET v2.0. So they removed the Fiber support from V2.0. Please refer this links for more details.

a. https://blogs.msdn.com/dinoviehland/archive/2005/09/15/469642.aspx

b. https://blogs.msdn.com/cbrumme/archive/2003/04/15/51351.aspx

 

CoRoutine - Yield

We still have native support to Fibers. Only managed support is not there. We can Pinvoke and use fibers whenever we want. Or use Managed Extentions for C++ to implement class that internally used native fibers. We all might have used yield keyword before the return keyword from the method so as to maintain the state of the method. This link from MSDN Magazine uses the later technique to implement yield functionality. It is very interesting. One may not want to miss it. https://msdn.microsoft.com/en-us/magazine/cc164086.aspx

 Fiber or Thread: Which is best?

Simple. One size does not fit for all. You will have to choose whatever works for you. But before you choose one, why not get an expert idea from this link - https://blogs.msdn.com/cbrumme/archive/2003/04/15/51351.aspx

Tomorrow let us jump into Threadpool and explore.

Comments