<commit_before>#include "binary_semaphore.h"

#include <unistd.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <limits.h>

BinarySemaphore::BinarySemaphore():
   _flag(false),
   _numWaiting(0),
   _futx(0)
{}

BinarySemaphore::~BinarySemaphore()
{}

void
BinarySemaphore::wait()
{
   _lock.acquire();
   while (!_flag)
   {
      _numWaiting ++;
      _futx = 0;

      _lock.release();

      syscall(SYS_futex, (void*) &_futx, FUTEX_WAIT, 0, NULL, NULL, 0);

      _lock.acquire();
      _numWaiting --;
   }

   _flag = false;
   _lock.release();
}

void
BinarySemaphore::signal()
{
   _lock.acquire();

   _flag = true;
   if (_numWaiting > 0)
   {
      _futx = 1;
      syscall(SYS_futex, (void*) &_futx, FUTEX_WAKE, 1, NULL, NULL, 0);
   }

   _lock.release();
}

void
BinarySemaphore::broadcast()
{
   _lock.acquire();

   _flag = true;
   if (_numWaiting > 0)
   {
      _futx = 1;
      syscall(SYS_futex, (void*) &_futx, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
   }<commit_msg>[binary semaphore] Faster implementation of the binary semaphore<commit_after>#include "binary_semaphore.h"

#include <unistd.h>
#include <sys/syscall.h>
#include <linux/futex.h>
#include <limits.h>

BinarySemaphore::BinarySemaphore():
   _flag(false),
   _numWaiting(0),
   _futx(0)
{}

BinarySemaphore::~BinarySemaphore()
{}

void
BinarySemaphore::wait()
{
   _lock.acquire();
   while (!_flag)
   {
      _numWaiting ++;
      _futx = 0;

      _lock.release();

      syscall(SYS_futex, (void*) &_futx, FUTEX_WAIT, 0, NULL, NULL, 0);

      _lock.acquire();
   }

   _flag = false;
   _lock.release();
}

void
BinarySemaphore::signal()
{
   _lock.acquire();

   _flag = true;
   if (_numWaiting > 0)
   {
      _numWaiting --;
      _futx = 1;
      syscall(SYS_futex, (void*) &_futx, FUTEX_WAKE, 1, NULL, NULL, 0);
   }

   _lock.release();
}

void
BinarySemaphore::broadcast()
{
   _lock.acquire();

   _flag = true;
   if (_numWaiting > 0)
   {
      _futx = 1;
      syscall(SYS_futex, (void*) &_futx, FUTEX_WAKE, INT_MAX, NULL, NULL, 0);
   }
{'fraction_non_alphanumeric': 0.16089712335446124, 'fraction_numerical': 0.011701608971233545, 'mean_word_length': 3.1204819277108435, 'pattern_counts': {'":': 0, '<': 11, '<?xml version=': 0, '>': 15, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1760506', 'n_tokens_mistral': 911, 'n_tokens_neox': 860, 'n_words': 155}