/* condvar.cc
 * This file belongs to Worker, a file manager for UN*X/X11.
 * Copyright (C) 2002-2014 Ralf Hoffmann.
 * You can contact me at: ralf@boomerangsworld.de
 *   or http://www.boomerangsworld.de/worker
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */

#include "condvar.h"

CondVar::CondVar() : MutEx()
{
  pthread_cond_init( &_condvar, NULL );
}

CondVar::~CondVar()
{
  pthread_cond_destroy( &_condvar );
}

void CondVar::wait()
{
  int oldcount;

    {
        std::unique_lock< std::mutex > lck( m_owner_data_mutex );

        //TODO another way of handling this case could be locking the mutex
        if ( _owner != pthread_self() ) {
            return;
        }

        _owner = 0;
        oldcount = _owncount;
        _owncount = 0;
    }

#ifdef THREAD_DEBUG
    printf( "(%d,%p)::wait %d\n", pthread_self(), this, oldcount );
#endif
    pthread_cond_wait( &_condvar, &_mutex );
#ifdef THREAD_DEBUG
    printf( "(%d)::wait end\n", pthread_self() );
#endif

    {
        std::unique_lock< std::mutex > lck( m_owner_data_mutex );

        _owner = pthread_self();
        _owncount = oldcount;
    }

    return;
}

void CondVar::signal()
{
  pthread_cond_signal( &_condvar );

#ifdef THREAD_DEBUG
  printf( "(%d,%p)signal::count %d\n", pthread_self(), this, _owncount );
#endif
}

void CondVar::bcast()
{
  pthread_cond_broadcast( &_condvar );
}
