Click here to Skip to main content
15,893,668 members
Articles / Programming Languages / C++

A C++ Cross-Platform Thread Class

Rate me:
Please Sign up or sign in to vote.
4.56/5 (26 votes)
15 Nov 20034 min read 518.7K   1.8K   49  
Write portable object-oriented threads that work on Win32 and Posix-Compliant systems without modification.
/////////////////////////////////////////////////////////////////////
//  Written by Phillip Sitbon
//  Copyright 2003
//
//  Win32/Semaphore.h
//    - Resource counting mechanism
//
/////////////////////////////////////////////////////////////////////
#ifndef _Semaphore_Win32_
#define _Semaphore_Win32_

#include "Win32.h"

#define SEM_VALUE_MAX ((int) ((~0u) >> 1))

class Semaphore
{
  HANDLE S;
  void operator=(const Semaphore &S){}
  Semaphore(const Semaphore &S){}

  public:
  Semaphore( int init = 0 )
  { S = CreateSemaphore(0,init,SEM_VALUE_MAX,0); }

  virtual ~Semaphore()
  { CloseHandle(S); }

  void Wait() const
  { WaitForSingleObject((HANDLE)S,INFINITE); }

  int Wait_Try() const
  { return ((WaitForSingleObject((HANDLE)S,INFINITE)==WAIT_OBJECT_0)?0:EAGAIN); }

  int Post() const
  { return (ReleaseSemaphore((HANDLE)S,1,0)?0:ERANGE); }

  int Value() const
  { LONG V = -1; ReleaseSemaphore((HANDLE)S,0,&V); return V; }

  void Reset( int init = 0 )
  {
    CloseHandle(S);
    S = CreateSemaphore(0,init,SEM_VALUE_MAX,0);
  }
};

#endif // !_Semaphore_Win32_

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Web Developer
United States United States
I am a student at Portland State University in Portland, Oregon majoring in Mathematics and minoring in Computer Science and Physics.

Comments and Discussions