windows c + + tråd venter på kø data-push

Indlæg af Hanne Mølgaard Plasc

Problem



Mit program er konfigureret som følger:

Der er en tråd-sikker kø klasse, en tråd skubber data på den mens du sidder i en uendelig loop og en anden tråd dukker data væk fra det, mens du sidder i en uendelig sløjfe. Jeg forsøger at tænke på en måde at bruge Windows-begivenheder eller en anden mekanisme til at lave thread\_1 (nedenfor), vent i den uendelige, mens sløjfen og kun gentage, når kødybden er større end eller lig med 1.


class thread-safe\_Queue
{
 public:
  push();
  pop();
};

DWORD thread\_1()
{
 while(1)
 {
  // wait for thread-safe queue to have data on it
  // pop data off
  // process data
 }
}

DWORD thread\_2()
{
 while(1)
 {
  // when data becomes available, push data onto thread-safe queue
 }
}

Bedste reference


Jeg tror, ​​det kan gøre tricket. Aflede klasse Hændelse og overbelast processen ().


#include <process.h> // Along with all the normal windows includes

//*********************************************
using namespace os;

Mutex globalQueueMutex;

class QueueReader : public Event
{
public:
    virtual void Process()
    {
      // Lock the queue
      Locker l(globalQueueMutex);
      // pop data off
      // process data
      return; // queue will automatically unlock
    }
};

QueueReader myQueueReader;

//*********************************************
// The queue writer would have functions like :
void StartQueueReader()
{
    Thread(QueueReader::StartEventHandler, &myQueueReader);
}
void WriteToQueue()
{
    Locker l(globalQueueMutex);
    // write to the queue
    myQueueReader.SignalProcess(); // tell reader to wake up
}
// When want to shutdown
void Shutdown()
{
    myQueueReader.SignalShutdown();
}


Her er de klasser, der udfører magien.


namespace os {

// **********************************************************************
/// Windows implementation to spawn a thread.
static uintptr\_t Thread (void (*StartAddress)(void *), void *ArgList)
{
  return \_beginthread(StartAddress, 0, ArgList);
}

// **********************************************************************
/// Windows implementation of a critical section.
class Mutex
{
public:
  // Initialize section on construction
  Mutex() { InitializeCriticalSection( &cs\_ ); }
  // Delete section on destruction
  ~Mutex() { DeleteCriticalSection( &cs\_ ); }
  // Lock it
  void lock() { EnterCriticalSection( &cs\_ ); }
  // Unlock it
  void unlock() { LeaveCriticalSection( &cs\_ ); }

private:
  CRITICAL\_SECTION cs\_;
}; // class Mutex

/// Locks/Unlocks a mutex
class Locker
{
public:
  // Lock the mutex on construction
  Locker( Mutex& mutex ): mutex\_( mutex ) { mutex\_.lock(); }
  // Unlock on destruction
  ~Locker() { mutex\_.unlock(); }
private:
  Mutex& mutex\_;
}; // class Locker

// **********************************************************************
// Windows implementation of event handler
#define ProcessEvent  hEvents[0]
#define SetTimerEvent hEvents[1]
#define ShutdownEvent hEvents[2]

/// Windows implementation of events
class Event
{
  /// Flag set when shutdown is complete
  bool Shutdown;
  /// Max time to wait for events
  DWORD Timer;
  /// The three events  - process, reset timer, and shutdown
  HANDLE hEvents[3];

public:
  /// Timeout is disabled by default and Events assigned
  Event( DWORD timer = INFINITE) : Timer(timer)
  {
    Shutdown = false;
    ProcessEvent = CreateEvent( NULL,TRUE,FALSE,NULL );
    SetTimerEvent = CreateEvent( NULL,TRUE,FALSE,NULL );
    ShutdownEvent = CreateEvent( NULL,TRUE,FALSE,NULL );
  }

  /// Close the event handles
  virtual ~Event()
  {
    CloseHandle(ProcessEvent);
    CloseHandle(SetTimerEvent);
    CloseHandle(ShutdownEvent);
  }

  /// os::Thread calls this to start the Event handler
  static void StartEventHandler(void *pMyInstance)
    { ((Event *)pMyInstance)->EventHandler(); }
  /// Call here to Change/Reset the timeout timer
  void ResetTimer(DWORD timer)  { Timer = timer; SetEvent(SetTimerEvent); }
  /// Set the signal to shutdown the worker thread processing events
  void SignalShutdown() { SetEvent(ShutdownEvent); while (!Shutdown) Sleep(30);}
  /// Set the signal to run the process
  void SignalProcess() { SetEvent(ProcessEvent); }

protected:
  /// Overload in derived class to process events with worker thread
  virtual void Process(){}
  /// Override to process timeout- return true to terminate thread
  virtual bool Timeout(){ return true;}

  /// Monitor thread events
  void EventHandler()
  {
    DWORD WaitEvents;
    while (!Shutdown)
    {
      // Wait here, looking to be signaled what to do next
      WaitEvents = WaitForMultipleObjects(3, hEvents, FALSE, Timer);

      switch (WaitEvents)
      {
        // Process event - process event then reset for the next one
        case WAIT\_OBJECT\_0 + 0:
          Process();
          ResetEvent(ProcessEvent);
          break;

        // Change timer event - see ResetTimer(DWORD timer)
        case WAIT\_OBJECT\_0 + 1:
          ResetEvent(SetTimerEvent);
          continue;

        // Shutdown requested so exit this thread
        case WAIT\_OBJECT\_0 + 2:
          Shutdown = true;
          break;

        // Timed out waiting for an event
        case WAIT\_TIMEOUT:
          Shutdown = Timeout();
          break;

        // Failed - should never happen
        case WAIT\_FAILED:
          break;

        default:
          break;
      }
    }
  }


};

} // namespace os

Andre referencer 1


Hvad med denne ene (jeg antager, at du er bekendt med arrangementsmekanismer).


1.


thread\_safe\_Queue::push(something)
{
// lock the queue
...
// push object
// Signal the event
SetEvent(notification);

// unlock the queue
}


2.


thread\_safe\_Queue::pop(something)
{
WaitForSingleObject(notification);
// lock the queue
...
// get object
// reset the event
if (queue is empty)
  ResetEvent(notification);

// unlock the queue
}


3. thread\_1 prøver bare at pope objektet og håndtere det. Som noget skubbes, er arrangementet aktiveret, så pop kan med succes kaldes. Ellers vil det vente inde i pop. Faktisk kan du bruge andre synkroniseringsobjekter som mutexes eller kritiske afsnit i stedet for begivenhederne i dette tilfælde.


UPDATE. Eksterne begivenheder:
tråd 1:


void thread\_1()
  {
  while(1)
    {
    WaitForSingleObject(notification);
    if (!pop(object))  // pop should return if there are any objects left in queue
      SetEvent(notification);    
    }
  }


thread\_2


void thread\_2()
  {
  while(1)
    {
    // push the object and than signal event
    ResetEvent(notification)
    }
  }

Andre referencer 2


Du kan bruge navngivne begivenheder. Hver tråd ville kalde CreateEvent, der passerer i samme navn. Brug derefter WaitForMultipleObjects til at vente på enten kørelateret begivenhed eller slut programbegivenhed. Pop-tråden vil vente på queue\_has\_data og end\_program events. Skubttråden vil vente på data\_available og end\_program begivenheder og indstille queue\_has\_data begivenheden, når den sætter noget i køen.