c++ - Lightest synchronization primitive for worker thread queue -


i implement worker thread work item queuing, , while thinking problem, wanted know if i'm doing best thing.

the thread in question have have thread local data (preinitialized @ construction) , loop on work items until condition met.

pseudocode:

volatile bool run = true;  int workerthread(param) {     localclassinstance c1 = new c1();     [other initialization]      while(true) {         [lock]         [unqueue work item]         [unlock]         if([hasworkitem]) {             [process data]             [postmessage pointer data]         }         [sleep]          if(!run)             break;     }      [uninitialize]     return 0; } 

i guess locking via critical section, queue std::vector or std::queue, maybe there better way.

the part sleep doesn't great, there lot of sleep big sleep values, or lot's of locking when sleep value small, , that's unnecessary.

but can't think of waitforsingleobject friendly primitive use instead of critical section, there might 2 threads queuing work items @ same time. event, seems best candidate, can loose second work item if event set already, , doesn't guarantee mutual exclusion.

maybe there better approach interlockedexchange kind of functions leads less serialization.

p.s.: might need preprocess whole queue , drop obsolete work items during unqueuing stage.

there multitude of ways this.

one option use semaphore waiting. semaphore signalled every time value pushed on queue, worker thread block if there no items in queue. still require separate synchronization on queue itself.

a second option use manual-reset event set when there items in queue , cleared when queue empty. again, need separate synchronization on queue.

a third option have invisible message-only window created on thread, , use special wm_user or wm_app message post items queue, attaching item message via pointer.

another option use condition variables. native windows condition variables work if you're targetting windows vista or windows 7, condition variables available windows xp boost or implementation of c++0x thread library. example queue using boost condition variables available on blog: http://www.justsoftwaresolutions.co.uk/threading/implementing-a-thread-safe-queue-using-condition-variables.html


Comments

Popular posts from this blog

c++ - Convert big endian to little endian when reading from a binary file -

gdi+ - WxWidgets draw a bitmap with opacity -

C#: Application without a window or taskbar item (background app) that can still use Console.WriteLine() -