2021年4月6日星期二

which thread run garbage collection in .net?

Below is the quote from a book:

When a thread allocates an object that pushes generation 0 over its budget, the GC first suspends all threads and then determines which generations to collect. If the garbage collector needs to collect generation 0 or 1, it proceeds as normal.

Let's say we have three concurrent threads, threa 1, threa 2 and thead 3, at some point of time, thread 3 allocate a new object to heap, which causes the budget of generation 0 to be full, GC needs to run.

My quesitons are:

Q1-which thread runs the GC?

Q2-If it is thread 3 to run GC, my understanding is, when thread 3 runs GC, somwhow thread 3's context needs to be saved first, then it stop thread 1 and thread 2 then do the GC, when it finishes GC, thread 3 needs to restore its prevous thread context to execute what it prevously execute before GC happened. Is my understanding correct?

Q3-If my understanding to Q2 is correct, saving and restoring thread context is expensive work, why not CLR create a new dedicate thread to run GC instead of using existing thread to run GC?

P.S. I know CLR uses a dedicate thread to collect generation 2 objects, this question is about genration 0 and generation 1 collection, why not also use a dedicate thread to collect genration 0 and generation 1 objects?

https://stackoverflow.com/questions/66979370/which-thread-run-garbage-collection-in-net April 07, 2021 at 11:57AM

没有评论:

发表评论