Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How often does a managed thread switch OS threads?

I understand that managed threads are not guaranteed to run on the same OS thread.

If the CLR may switch a managed thread between OS threads, how often does this happen? What influence the frequency?

I've got a separate question on how to stop the switching from happening. Second prize for me would be for this to not happen too often (less than once a minute would be fine).

like image 804
biozinc Avatar asked Dec 30 '09 09:12

biozinc


2 Answers

It completely depends on the host. There is no guarantee as to when or where a thread switch might take place (if at all), given any particular host.

However, since .NET 2.0, you have been able to call the static BeginThreadAffinity method to notify the host that the code that is running depends on the identity of the underlying OS thread:

http://msdn.microsoft.com/en-us/library/system.threading.thread.beginthreadaffinity(VS.80).aspx

Of course, make sure you call the EndThreadAffinity method when your thread is done (I'm not sure what happens if you just let the thread end without calling EndThreadAffinity. I can't imagine it would have an impact, but it's better to be explicit in this matter, IMO):

http://msdn.microsoft.com/en-us/library/system.threading.thread.endthreadaffinity(VS.80).aspx

like image 157
casperOne Avatar answered Nov 15 '22 09:11

casperOne


As far as I am aware the current implementation of the CLR maps managed threads to OS threads. However, as the documentation says this is not guaranteed, i.e. it is an implementation detail so you can't assume anything. It could change, but even if it doesn't the advice of the documentation is that you shouldn't rely on a one to one mapping.

As casperOne points out you can set thread affinity but apart from that, there are no guarantees.

like image 25
Brian Rasmussen Avatar answered Nov 15 '22 08:11

Brian Rasmussen