|
-
July 4th, 2011, 12:12 PM
#15
Re: Win32/queue(STL)/threads?
>> while ( wd->dwQueued )
This is unsynchronized access to a shared variable. Can't do that.
Here is something simple you could do:
Code:
class MTCounter : public no_copy
{
Event m_zeroEvent;
CriticalSection m_cs;
int m_counter;
typedef CriticalSection::scoped_lock lock;
public:
MTCounter() : m_counter(0)
{
if (!m_zeroEvent.Create(true, true)) // manual reset, signaled
throw std::runtime_error("MTCounter: failed to create event");
}//constructor
void increment()
{
lock l(m_cs);
++m_counter;
m_zeroEvent.Reset();
}//increment
void decrement()
{
lock l(m_cs);
if (m_counter == 0)
throw std::runtime_error("MTCounter::decrement: count==0");
--m_counter;
if (m_counter == 0)
m_zeroEvent.Signal();
}//decrement
bool wait_zero(DWORD to = INFINITE)
{
return ::WaitForSingleObject(m_zeroEvent, to) == WAIT_OBJECT_0;
}//wait_zero
};//MTCounter
So add an MTCounter member to WATCH_DATA. Before the producer calls enqueue(), call MTCounter::increment(). When the consumer thread is done making any more references to the WATCH_DATA pointer, call MTCounter::decrement(). Producer thread calls wait_zero before deleting and exiting. This only works if there is a one-to-one correlation between producer and consumer, and each producer has it's own unique WATCH_DATA instance.
>> EVENT_DATA *ed = new EVENT_DATA(wd, p);
I'm assuming that all data within WATCH_DATA pointer is read-only by the consumer - and the consumer does not touch WATCH_DATA::pBuffer.
I'm also assuming you are copying data out of p within the constructor, and not keeping any references to p or its memory (which belongs to the producer).
>> delete wd;
I also assume that WATCH_DATA's destructor closes handles, and de-allocates any dynamic memory it owns.
>> Mine has (in the last couple days) been boiled down to this.
Your consumer thread should look a lot different from the "QueueThread" code that was originally posted as well :)
gg
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|