What is the C++ equivalent for AutoResetEvent under Linux?

The description of AutoResetEvent in MSDN

I'm trying to port a Thread Pool implemented in C# to C++ under Linux. I don't know which functions I should use that have similar behaviors to "AutoResetEvent".


An AutoResetEvent is most akin to a binary semaphore. People saying "conditional variables" aren't wrong per se, but condition variables are used in similar situations, rather than being similar objects. You can implement an (unnamed) AutoResetEvent on top of condition variables:

#include <pthread.h>
#include <stdio.h>

class AutoResetEvent
  explicit AutoResetEvent(bool initial = false);

  void Set();
  void Reset();

  bool WaitOne();

  AutoResetEvent(const AutoResetEvent&);
  AutoResetEvent& operator=(const AutoResetEvent&); // non-copyable
  bool flag_;
  pthread_mutex_t protect_;
  pthread_cond_t signal_;

AutoResetEvent::AutoResetEvent(bool initial)
: flag_(initial)
  pthread_mutex_init(&protect_, NULL);
  pthread_cond_init(&signal_, NULL);

void AutoResetEvent::Set()
  flag_ = true;

void AutoResetEvent::Reset()
  flag_ = false;

bool AutoResetEvent::WaitOne()
  while( !flag_ ) // prevent spurious wakeups from doing harm
    pthread_cond_wait(&signal_, &protect_);
  flag_ = false; // waiting resets the flag
  return true;


AutoResetEvent event;

void *otherthread(void *)
  printf("Hello from other thread!\n");
  return NULL;

int main()
  pthread_t h;
  pthread_create(&h, NULL, &otherthread, NULL);
  printf("Hello from the first thread\n");

  pthread_join(h, NULL);
  return 0;

If however, you need named auto reset events, you'll likely want to look at semaphores, and may have a slightly more difficult time translating your code. Either way I would look careful at the documentation for pthreads on your platform, condition variables and auto reset events are not the same and do not behave the same.

Need Your Help

Add/Remove polylines using Google Maps API using javascript not working

javascript google-maps

Having some problems with the javascript Google maps API, specifically poly lines.

Using \ character in textarea

javascript string textarea

This might be an stupid question for many of you, but I'm hitting a wall with the stupidest thing.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.