Windows recursive critical section not working

I have the following code written in C ++ / CX:

TaskPool^ TaskPool::Instance::get()
{
    // Prevent acquiring the critical section for a static initialization
    // after it been properly initialized.
    if (TaskPool::_instance == nullptr) {

        static CRITICAL_SECTION section;

        CriticalSection lock(&section);

        if (TaskPool::_instance == nullptr) {
            _instance = ref new TaskPool();
            InitializeCriticalSection(GetCriticalSection());
        }
    }
    return _instance;
}

TaskPool^ TaskPool::_instance;
CRITICAL_SECTION TaskPool::_criticalSection;

void Threading::TaskPool::TaskRun(Concurrency::task<void> & task)
{
    Log::LogMessage(this->GetType()->FullName, Level::Debug, "TaskRun [entering]");
    EnterCriticalSection(GetCriticalSection());
    Log::LogMessage(this->GetType()->FullName, Level::Debug, "TaskRun [entered]");

    create_task(task).then([this]() {
        Log::LogMessage(this->GetType()->FullName, Level::Debug, "TaskRun [leaving]");
        LeaveCriticalSection(GetCriticalSection());
        Log::LogMessage(this->GetType()->FullName, Level::Debug, "TaskRun [left]");
    });
}

TaskPool- a task manager that uses CRITICAL_SECTIONconcorrent to send tasks synchronously. I read here and confirmed in several other places that critical sections are reentrant. However, I cannot reproduce this behavior.

Threading.TaskPool <Debug> TaskRun [entering]
Threading.TaskPool <Debug> TaskRun [entered]
Threading.TaskPool <Debug> TaskRun [leaving]
Threading.TaskPool <Debug> TaskRun [left]
Threading.TaskPool <Debug> TaskRun [entering]
Threading.TaskPool <Debug> TaskRun [entering]

As you can see, several tasks are sent. However, although the first task seems to work well, other tasks added to the pool are not sent. For some reason, a critical section is not introduced, and the stream seems to be hanging. If critical sections are recursive, what else can explain this behavior?

+4

Source: https://habr.com/ru/post/1666932/


All Articles