locked
Threadpool and completion handler RRS feed

  • Question

  • Hi all,

    I'm working on some thread pool. Our game currently has a task system which I'm trying to do in WinRT.

    So far everything looks ok. However I have a question over the completion handlers are set-up.

    I have the follow two lines of code:

    m_workItem = ThreadPool::RunAsync(m_workItemHandler);

    m_workItem->Completed = m_completionHandler;

    So my question is: is assigning the completion handler thread safe? Naively looking at the code it is not obvious why this is a good idea. Surely the call to RunAsync cause the work item delegate to run in another thread. However the completion handler is not assigned until the next line.

    For example the following could happened:

      • Thread 1 -> Call RunAysnc.
      • Thread 1 -> Context switched out, does to sleep
      • ThreadPool thread -> Runs the work item
      • ThreadPool thread -> The work item finishes and the delegate function ends.
      • Thread 1 -> Wakes up.
      • Thread 1 -> Assigns the completion delegate to the workitem.

    So could the work item finish before the completion delegate is assigned? If this is not possible then how is that prevented?

    If the assignment of the completion delegate is done after the work item has finished, is it called immediately or never?

    Thanks

    • Edited by Mortom Wednesday, February 20, 2013 8:51 PM
    Wednesday, February 20, 2013 8:50 PM

Answers