Waiting for win32 threads

I have a fully thread-safe FIFO ( TaskList) structure for storing task classes, several threads, some of which create and save a task, while others process tasks. TaskListthe class has a method pop_front()that returns the first task, if there is at least one. Otherwise, it returns NULL.
Here is an example of a processing function:

TaskList tlist;

unsigned _stdcall ThreadFunction(void * qwe)
{
    Task * task;
    while(!WorkIsOver) // a global bool to end all threads.
    {
        while(task = tlist.pop_front())
        {
            // process Task
        }
    }
    return 0;
}

, , (while(!WorkIsOver)), . - , . , , , .

?

PS. winapi, Boost TBB . , , . . , .

+2
7

, DevStudio, , [IO Completion Ports]. , .

. 3 API, , , . PostQueuedCompletionStatus , GetQueuedCompletionStatus. , TerminateThread , . - , , ​​ , , ​​ ~ 100%.

NB. TerminateThread API. , , , , , . TerminateThread . , , , TerminateThread - , , .

+7
  • , , .
  • , , ::ReleaseSemaphore, ,
  • ::WaitForSingleObject() - -, , . , , .
+2

, Herb Sutter Concurrency, .

+2

/ - .

Windows, Boost. , , Windows, Boost, API Win32 , .

+1

? Windows .

0
  • windows threadpool!
  • api call WaitForSingleObject WaitForMultipleObjects.
  • SwitchToThread api .
0

TaskList - wait_until_not_empty, . , (1000) ( - ) . TaskList, auto- reset, , . pop/push, :

WaitableTaskList::WaitableTaskList()
{
  // task list is empty upon creation
  non_empty_event = CreateEvent(NULL, FALSE, FALSE, NULL);
}

Task* WaitableTaskList::wait_and_pop_front(DWORD timeout)
{
  WaitForSingleObject(non_empty_event, timeout);
  // .. handle error, return NULL on timeout

  Task* result = task_list.pop_front();

  if (!task_list.empty())
    SetEvent(non_empty_event);

  return result;
}

void WaitableTaskList::push_back(Task* item)
{
  task_list.push_back(item);
  SetEvent(non_empty_event);
}

, wait_and_pop_front().

EDIT: This is actually a bad solution. There is a way for un_empty_event to be raised, even if the list is empty. The situation requires 2 threads trying a pop list, and the list contains 2 elements. If the list becomes empty between if and SetEvent, we will have an incorrect state. Obviously, we also need to implement synchronization. At this moment, I will again review the simple Dream :-)

0
source

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


All Articles