Thread overview
Unexpected threads observed before main()
Mar 01, 2021
Keivan Shah
Mar 01, 2021
rikki cattermole
Mar 01, 2021
Keivan Shah
Mar 01, 2021
rikki cattermole
Mar 01, 2021
Keivan Shah
March 01, 2021
I had recently updated my dmd version to latest, i.e from 2.076.1 (I know, sorry) to 2.095.0 and suddenly my code has started spawning extra threads which were not there before with no obvious reasons, after trying to simplify and identify the cause as much as possible, I have come up with this snippet of code:

module test;
// PART 1
class SomeClass
{
}
static this() // Works in both cases, "static this" as well as "shared static this"
{
new SomeClass;
}

// PART 2
class TestThread
{
    static this() // Works in both cases, "static this" as well as "shared static this"
    {
        import core.memory;
        GC.collect;
    }
}

void main() // Voila! Extra 5 threads before starting main!
{
    import std;
    import core.thread;
    auto pid = getpid;
    // Linux hack to prevent having to do `top` and check num of threads
    writeln(" NumThreads: ", dirEntries("/proc/" ~ pid.to!string ~ "/task/", SpanMode.shallow).array.length);
    // writeln("PID: ", pid, " NumThreads: ", Thread.getAll.length); // This doesn't seem to give the right number
    while(true){}
}

This when running on my local Linux machine with dmd-2.095.0 shows that 6 threads are running but on running with dmd-2.076.1 (Sorry, haven't tried on all other dmds in between) gives only 1 thread. Something seems to be off here and to make it even more confusing, when running this on run.dlang.io, it seems to only give 1 thread. Is there something obviously wrong that I am doing or this could be a potential bug in D runtime?
March 01, 2021
Do you still get them when you call your app like this?

./app --DRT-gcopt=parallel:0
March 01, 2021
On Monday, 1 March 2021 at 06:50:42 UTC, rikki cattermole wrote:
> Do you still get them when you call your app like this?
>
> ./app --DRT-gcopt=parallel:0

Wow, Not getting with "--DRT-gcopt=parallel:0", Thanks a lot, didn't know GC had a parallel option that can be controlled(https://dlang.org/spec/garbage.html#gc_parallel). If possible, Can you also help me understand that why are the threads not despawned once the GC is done collecting in this example?
March 01, 2021
On 01/03/2021 8:02 PM, Keivan Shah wrote:
> If possible, Can you also help me understand that why are the threads not despawned once the GC is done collecting in this example?

There was a PR about this ages ago.

But one thing to consider is that keeping threads around not doing anything doesn't cost anything. But spinning up will cost something.

So it is debatable if it is a good idea to get rid of them once done (even if delayed).
March 01, 2021
On Monday, 1 March 2021 at 09:03:32 UTC, rikki cattermole wrote:
> So it is debatable if it is a good idea to get rid of them once done (even if delayed).

Makes sense, Thanks a lot for the quick help!