[Issue 22358] Allocations from foreign threads lead to crash

d-bugmail at puremagic.com d-bugmail at puremagic.com
Tue Oct 5 20:36:50 UTC 2021


https://issues.dlang.org/show_bug.cgi?id=22358

thomas.bockman at gmail.com changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |thomas.bockman at gmail.com

--- Comment #3 from thomas.bockman at gmail.com ---
It appears to be a race condition between `thread_attachThis` and `GC.collect`.
Serializing them prevents the crash:

//////////////////////////////////////////////////
import core.sys.posix.pthread;
import core.memory;
import core.sync.mutex;
import core.thread;
import std.stdio;

enum allocCount = 1000;
enum allocSize = 1000;
enum threadCount = 100;
enum collectCount = 1000;

shared Mutex serialize;
shared static this() {
    serialize = new shared Mutex;
}

extern(C) void* foo(void*)
{
    serialize.lock_nothrow();
    thread_attachThis();
    serialize.unlock_nothrow();

    scope(exit)
        thread_detachThis();

    foreach(_; 0..allocCount) {
        new int;
        new int[allocSize];
    }

    writeln(`foo done`);
    return null;
}

void main()
{
    pthread_t thread;

    foreach(_; 0..threadCount) {
        auto status = pthread_create(&thread, null, &foo, null);
        assert(status == 0);

        foreach(i; 0..collectCount) {
            serialize.lock_nothrow();
            GC.collect();
            serialize.unlock_nothrow();
        }

        pthread_join(thread, null);
    }

    writeln(`main done`);
}
//////////////////////////////////////////////////

--


More information about the Digitalmars-d-bugs mailing list