/*
All rights reserved.

This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org

*/

#include "toplevelfixture.hpp"
#include "utilities.hpp"
#include <boost/make_shared.hpp>
#include <boost/test/unit_test.hpp>

#include <qle/termstructures/interpolatedyoycapfloortermpricesurface.hpp>

#include <ql/indexes/inflation/euhicp.hpp>
#include <ql/math/interpolations/bilinearinterpolation.hpp>
#include <ql/math/interpolations/linearinterpolation.hpp>
#include <ql/math/matrix.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/termstructures/inflation/piecewisezeroinflationcurve.hpp>
#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/time/calendars/target.hpp>

using namespace QuantExt;
using namespace QuantLib;
using namespace boost::unit_test_framework;

BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)

BOOST_AUTO_TEST_SUITE(CapFloordTermPriceSurfaceTest)

{

    BOOST_TEST_MESSAGE("Testing InterpolatedYoyCapFloorTermPriceSurface");

    Date asof_ = Date(18, July, 2016);
    Settings::instance().evaluationDate() = asof_;

    Handle<YieldTermStructure> nominalTs =
        Handle<YieldTermStructure>(boost::make_shared<FlatForward>(0, TARGET(), 0.005, Actual365Fixed()));

    std::vector<Rate> capStrikes;
    capStrikes.push_back(0.01);
    capStrikes.push_back(0.02);
    capStrikes.push_back(0.03);
    capStrikes.push_back(0.04);
    capStrikes.push_back(0.05);

    std::vector<Rate> floorStrikes;
    floorStrikes.push_back(-0.02);
    floorStrikes.push_back(-0.01);
    floorStrikes.push_back(0.0);
    floorStrikes.push_back(0.01);
    floorStrikes.push_back(0.02);

    std::vector<Period> maturities;
    maturities.push_back(Period(2, Years));
    maturities.push_back(Period(5, Years));
    maturities.push_back(Period(7, Years));
    maturities.push_back(Period(10, Years));
    maturities.push_back(Period(15, Years));
    maturities.push_back(Period(20, Years));

    Matrix capPrice(capStrikes.size(), maturities.size(), Null<Real>()),
        floorPrice(floorStrikes.size(), maturities.size(), Null<Real>());

    capPrice[0][0] = 0.00874;
    capPrice[1][0] = 0.00146;
    capPrice[2][0] = 0.00019;
    capPrice[3][0] = 0.00003;
    capPrice[4][0] = 0.00001;
    capPrice[0][1] = 0.02946;
    capPrice[1][1] = 0.00793;
    capPrice[2][1] = 0.00214;
    capPrice[3][1] = 0.00074;
    capPrice[4][1] = 0.00032;
    capPrice[0][2] = 0.04626;
    capPrice[1][2] = 0.01448;
    capPrice[2][2] = 0.00481;
    capPrice[3][2] = 0.00206;
    capPrice[4][2] = 0.00107;
    capPrice[0][3] = 0.07622;
    capPrice[1][3] = 0.02778;
    capPrice[2][3] = 0.01106;
    capPrice[3][3] = 0.00565;
    capPrice[4][3] = 0.00343;
    capPrice[0][4] = 0.13218;
    capPrice[1][4] = 0.05476;
    capPrice[2][4] = 0.0245;
    capPrice[3][4] = 0.01393;
    capPrice[4][4] = 0.00927;
    capPrice[0][5] = 0.18889;
    capPrice[1][5] = 0.08297;
    capPrice[2][5] = 0.03909;
    capPrice[3][5] = 0.02369;
    capPrice[4][5] = 0.01674;
    floorPrice[0][0] = 0.000000001;
    floorPrice[1][0] = 0.00005;
    floorPrice[2][0] = 0.00057;
    floorPrice[3][0] = 0.00415;
    floorPrice[4][0] = 0.01695;
    floorPrice[0][1] = 0.00005;
    floorPrice[1][1] = 0.00071;
    floorPrice[2][1] = 0.00259;
    floorPrice[3][1] = 0.01135;
    floorPrice[4][1] = 0.03983;
    floorPrice[0][2] = 0.00035;
    floorPrice[1][2] = 0.00131;
    floorPrice[2][2] = 0.00482;
    floorPrice[3][2] = 0.0169;
    floorPrice[4][2] = 0.05463;
    floorPrice[0][3] = 0.0014;
    floorPrice[1][3] = 0.0036;
    floorPrice[2][3] = 0.00943;
    floorPrice[3][3] = 0.02584;
    floorPrice[4][3] = 0.07515;
    floorPrice[0][4] = 0.00481;
    floorPrice[1][4] = 0.00904;
    floorPrice[2][4] = 0.01814;
    floorPrice[3][4] = 0.04028;
    floorPrice[4][4] = 0.10449;
    floorPrice[0][5] = 0.00832;
    floorPrice[1][5] = 0.01433;
    floorPrice[2][5] = 0.02612;
    floorPrice[3][5] = 0.05269;
    floorPrice[4][5] = 0.12839;

    // build a
    std::vector<Date> datesZCII;
    datesZCII.push_back(asof_ + 1 * Years);
    std::vector<Rate> ratesZCII;
    ratesZCII.push_back(1.1625);

    // build EUHICPXT fixing history
    Schedule fixingDatesEUHICPXT =
        MakeSchedule().from(Date(1, May, 2015)).to(Date(1, July, 2016)).withTenor(1 * Months);
    std::vector<Real> fixingRatesEUHICPXT(15, 100);

    Handle<ZeroInflationIndex> hEUHICPXT;
    boost::shared_ptr<EUHICPXT> ii = boost::shared_ptr<EUHICPXT>(new EUHICPXT(false));
    boost::shared_ptr<ZeroInflationTermStructure> cpiTS;
    for (Size i = 0; i < fixingDatesEUHICPXT.size(); i++) {
        ii->addFixing(fixingDatesEUHICPXT[i], fixingRatesEUHICPXT[i], true);
    };
    // now build the helpers ...
    std::vector<boost::shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > > instruments;
    for (Size i = 0; i < datesZCII.size(); i++) {
        Handle<Quote> quote(boost::shared_ptr<Quote>(new SimpleQuote(ratesZCII[i] / 100.0)));
        boost::shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > anInstrument(new ZeroCouponInflationSwapHelper(
            quote, Period(3, Months), datesZCII[i], TARGET(), ModifiedFollowing, Actual365Fixed(), ii, nominalTs));
        instruments.push_back(anInstrument);
    };

    Rate baseZeroRate = ratesZCII[0] / 100.0;
    boost::shared_ptr<PiecewiseZeroInflationCurve<Linear>> pCPIts(new PiecewiseZeroInflationCurve<Linear>(
        asof_, TARGET(), Actual365Fixed(), Period(3, Months), Monthly, false, baseZeroRate, instruments));
    pCPIts->recalculate();
    cpiTS = boost::dynamic_pointer_cast<ZeroInflationTermStructure>(pCPIts);

    boost::shared_ptr<EUHICPXT> zii(new EUHICPXT(false, Handle<ZeroInflationTermStructure>(pCPIts)));
    boost::shared_ptr<ZeroInflationIndex> zeroIndex = boost::dynamic_pointer_cast<ZeroInflationIndex>(zii);

    boost::shared_ptr<YoYInflationIndex> yoyIndex;

    yoyIndex =
        boost::make_shared<QuantExt::YoYInflationIndexWrapper>(zeroIndex, true, Handle<YoYInflationTermStructure>());

    QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> ys(
        0, Period(3, Months), yoyIndex, 1, nominalTs, Actual365Fixed(), TARGET(), Following, capStrikes, floorStrikes,
        maturities, capPrice, floorPrice);

    boost::shared_ptr<QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> > yoySurface =
        boost::make_shared<QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> >(ys);

    // check the cap and floor prices from the surface
    Real tol = 1.0E-8;
    for (Size i = 0; i < maturities.size(); i++) {
        Date m = yoySurface->yoyOptionDateFromTenor(maturities[i]);
        for (Size j = 0; j < capStrikes.size(); j++) {
            BOOST_CHECK_CLOSE(yoySurface->capPrice(m, capStrikes[j]), capPrice[j][i], tol);
        }
        for (Size j = 0; j < floorStrikes.size(); j++) {
            BOOST_CHECK_CLOSE(yoySurface->floorPrice(m, floorStrikes[j]), floorPrice[j][i], tol);
        }
    }
} // testInterpolatedYoyCapFloorTermPriceSurface

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()


/*
All rights reserved.

This file is part of ORE, a free-software/open-source library
for transparent pricing and risk analysis - http://opensourcerisk.org

*/

#include "toplevelfixture.hpp"
#include "utilities.hpp"
#include <boost/make_shared.hpp>
#include <boost/test/unit_test.hpp>

#include <qle/termstructures/interpolatedyoycapfloortermpricesurface.hpp>

#include <ql/indexes/inflation/euhicp.hpp>
#include <ql/math/interpolations/bilinearinterpolation.hpp>
#include <ql/math/interpolations/linearinterpolation.hpp>
#include <ql/math/matrix.hpp>
#include <ql/quotes/simplequote.hpp>
#include <ql/termstructures/inflation/piecewisezeroinflationcurve.hpp>
#include <ql/termstructures/volatility/equityfx/blackvariancesurface.hpp>
#include <ql/termstructures/yield/flatforward.hpp>
#include <ql/time/calendars/target.hpp>

using namespace QuantExt;
using namespace QuantLib;
using namespace boost::unit_test_framework;

BOOST_FIXTURE_TEST_SUITE(QuantExtTestSuite, qle::test::TopLevelFixture)

BOOST_AUTO_TEST_SUITE(CapFloordTermPriceSurfaceTest)

BOOST_AUTO_TEST_CASE(testInterpolatedYoyCapFloorTermPriceSurface) {

    BOOST_TEST_MESSAGE("Testing InterpolatedYoyCapFloorTermPriceSurface");

    Date asof_ = Date(18, July, 2016);
    Settings::instance().evaluationDate() = asof_;

    Handle<YieldTermStructure> nominalTs =
        Handle<YieldTermStructure>(boost::make_shared<FlatForward>(0, TARGET(), 0.005, Actual365Fixed()));

    std::vector<Rate> capStrikes;
    capStrikes.push_back(0.01);
    capStrikes.push_back(0.02);
    capStrikes.push_back(0.03);
    capStrikes.push_back(0.04);
    capStrikes.push_back(0.05);

    std::vector<Rate> floorStrikes;
    floorStrikes.push_back(-0.02);
    floorStrikes.push_back(-0.01);
    floorStrikes.push_back(0.0);
    floorStrikes.push_back(0.01);
    floorStrikes.push_back(0.02);

    std::vector<Period> maturities;
    maturities.push_back(Period(2, Years));
    maturities.push_back(Period(5, Years));
    maturities.push_back(Period(7, Years));
    maturities.push_back(Period(10, Years));
    maturities.push_back(Period(15, Years));
    maturities.push_back(Period(20, Years));

    Matrix capPrice(capStrikes.size(), maturities.size(), Null<Real>()),
        floorPrice(floorStrikes.size(), maturities.size(), Null<Real>());

    capPrice[0][0] = 0.00874;
    capPrice[1][0] = 0.00146;
    capPrice[2][0] = 0.00019;
    capPrice[3][0] = 0.00003;
    capPrice[4][0] = 0.00001;
    capPrice[0][1] = 0.02946;
    capPrice[1][1] = 0.00793;
    capPrice[2][1] = 0.00214;
    capPrice[3][1] = 0.00074;
    capPrice[4][1] = 0.00032;
    capPrice[0][2] = 0.04626;
    capPrice[1][2] = 0.01448;
    capPrice[2][2] = 0.00481;
    capPrice[3][2] = 0.00206;
    capPrice[4][2] = 0.00107;
    capPrice[0][3] = 0.07622;
    capPrice[1][3] = 0.02778;
    capPrice[2][3] = 0.01106;
    capPrice[3][3] = 0.00565;
    capPrice[4][3] = 0.00343;
    capPrice[0][4] = 0.13218;
    capPrice[1][4] = 0.05476;
    capPrice[2][4] = 0.0245;
    capPrice[3][4] = 0.01393;
    capPrice[4][4] = 0.00927;
    capPrice[0][5] = 0.18889;
    capPrice[1][5] = 0.08297;
    capPrice[2][5] = 0.03909;
    capPrice[3][5] = 0.02369;
    capPrice[4][5] = 0.01674;
    floorPrice[0][0] = 0.000000001;
    floorPrice[1][0] = 0.00005;
    floorPrice[2][0] = 0.00057;
    floorPrice[3][0] = 0.00415;
    floorPrice[4][0] = 0.01695;
    floorPrice[0][1] = 0

    floorPrice[1][1] = 0.00071;
    floorPrice[2][1] = 0.00259;
    floorPrice[3][1] = 0.01135;
    floorPrice[4][1] = 0.03983;
    floorPrice[0][2] = 0.00035;
    floorPrice[1][2] = 0.00131;
    floorPrice[2][2] = 0.00482;
    floorPrice[3][2] = 0.0169;
    floorPrice[4][2] = 0.05463;
    floorPrice[0][3] = 0.0014;
    floorPrice[1][3] = 0.0036;
    floorPrice[2][3] = 0.00943;
    floorPrice[3][3] = 0.02584;
    floorPrice[4][3] = 0.07515;
    floorPrice[0][4] = 0.00481;
    floorPrice[1][4] = 0.00904;
    floorPrice[2][4] = 0.01814;
    floorPrice[3][4] = 0.04028;
    floorPrice[4][4] = 0.10449;
    floorPrice[0][5] = 0.00832;
    floorPrice[1][5] = 0.01433;
    floorPrice[2][5] = 0.02612;
    floorPrice[3][5] = 0.05269;
    floorPrice[4][5] = 0.12839;

    // build a
    std::vector<Date> datesZCII;
    datesZCII.push_back(asof_ + 1 * Years);
    std::vector<Rate> ratesZCII;
    ratesZCII.push_back(1.1625);

    // build EUHICPXT fixing history
    Schedule fixingDatesEUHICPXT =
        MakeSchedule().from(Date(1, May, 2015)).to(Date(1, July, 2016)).withTenor(1 * Months);
    std::vector<Real> fixingRatesEUHICPXT(15, 100);

    Handle<ZeroInflationIndex> hEUHICPXT;
    boost::shared_ptr<EUHICPXT> ii = boost::shared_ptr<EUHICPXT>(new EUHICPXT(false));
    boost::shared_ptr<ZeroInflationTermStructure> cpiTS;
    for (Size i = 0; i < fixingDatesEUHICPXT.size(); i++) {
        ii->addFixing(fixingDatesEUHICPXT[i], fixingRatesEUHICPXT[i], true);
    };
    // now build the helpers ...
    std::vector<boost::shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > > instruments;
    for (Size i = 0; i < datesZCII.size(); i++) {
        Handle<Quote> quote(boost::shared_ptr<Quote>(new SimpleQuote(ratesZCII[i] / 100.0)));
        boost::shared_ptr<BootstrapHelper<ZeroInflationTermStructure> > anInstrument(new ZeroCouponInflationSwapHelper(
            quote, Period(3, Months), datesZCII[i], TARGET(), ModifiedFollowing, Actual365Fixed(), ii, nominalTs));
        instruments.push_back(anInstrument);
    };

    Rate baseZeroRate = ratesZCII[0] / 100.0;
    boost::shared_ptr<PiecewiseZeroInflationCurve<Linear>> pCPIts(new PiecewiseZeroInflationCurve<Linear>(
        asof_, TARGET(), Actual365Fixed(), Period(3, Months), Monthly, false, baseZeroRate, instruments));
    pCPIts->recalculate();
    cpiTS = boost::dynamic_pointer_cast<ZeroInflationTermStructure>(pCPIts);

    boost::shared_ptr<EUHICPXT> zii(new EUHICPXT(false, Handle<ZeroInflationTermStructure>(pCPIts)));
    boost::shared_ptr<ZeroInflationIndex> zeroIndex = boost::dynamic_pointer_cast<ZeroInflationIndex>(zii);

    boost::shared_ptr<YoYInflationIndex> yoyIndex;

    yoyIndex =
        boost::make_shared<QuantExt::YoYInflationIndexWrapper>(zeroIndex, true, Handle<YoYInflationTermStructure>());

    QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> ys(
        0, Period(3, Months), yoyIndex, 1, nominalTs, Actual365Fixed(), TARGET(), Following, capStrikes, floorStrikes,
        maturities, capPrice, floorPrice);

    boost::shared_ptr<QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> > yoySurface =
        boost::make_shared<QuantExt::InterpolatedYoYCapFloorTermPriceSurface<Bilinear, Linear> >(ys);

    // check the cap and floor prices from the surface
    Real tol = 1.0E-8;
    for (Size i = 0; i < maturities.size(); i++) {
        Date m = yoySurface->yoyOptionDateFromTenor(maturities[i]);
        for (Size j = 0; j < capStrikes.size(); j++) {
            BOOST_CHECK_CLOSE(yoySurface->capPrice(m, capStrikes[j]), capPrice[j][i], tol);
        }
        for (Size j = 0; j < floorStrikes.size(); j++) {
            BOOST_CHECK_CLOSE(yoySurface->floorPrice(m, floorStrikes[j]), floorPrice[j][i], tol);
        }
    }
} // testInterpolatedYoyCapFloorTermPriceSurface

BOOST_AUTO_TEST_SUITE_END()

BOOST_AUTO_TEST_SUITE_END()


/* src/common/tutorial/funcs.cpp */

/******************************************************************************
  These are user-defined functions that can be bound to a openGauss backend
  and called by openGauss to execute SQL functions of the same name.

  The calling format for these functions is defined by the CREATE FUNCTION
  SQL statement that binds them to the backend.

  NOTE: this file shows examples of "old style" function call conventions.
  See funcs_new.c for examples of "new style".
*****************************************************************************/

#include "postgres.h"
#include "knl/knl_variable.h" /* general openGauss declarations */

#include "executor/executor.h" /* for GetAttributeByName() */
#include "utils/geo_decls.h"   /* for point type */

PG_MODULE_MAGIC;

/* These prototypes just prevent possible warnings from gcc. */

int add_one(int arg);
float8* add_one_float8(float8* arg);
Point* makepoint(Point* pointx, Point* pointy);
text* copytext(text* t);
text* concat_text(text* arg1, text* arg2);
bool c_overpaid(HeapTupleHeader t, /* the current instance of EMP */
    int32 limit);

/* By Value */
int add_one(int arg)
{
    return arg + 1;
}

/* By Reference, Fixed Length */

{
    float8* result = (float8*)palloc(sizeof(float8));

    *result = *arg + 1.0;

    return result;
}

Point* makepoint(Point* pointx, Point* pointy)
{
    Point* new_point = (Point*)palloc(sizeof(Point));

    new_point->x = pointx->x;
    new_point->y = pointy->y;

    return new_point;
}

/* By Reference, Variable Length */
text* copytext(text* t)
{
    /*
     * VARSIZE is the total size of the struct in bytes.
     */
    text* new_t = (text*)palloc(VARSIZE(t));

    SET_VARSIZE(new_t, VARSIZE(t));

    /*
     * VARDATA is a pointer to the data region of the struct.
     */
    errno_t errorno = EOK;
    errorno = memcpy_s((void *) VARDATA(new_t), /* destination */
        VARSIZE(t) - VARHDRSZ),                 /* how many bytes */
        (void *) VARDATA(t),                    /* source */
        VARSIZE(t) - VARHDRSZ);                 /* how many bytes */
    securec_check(errorno, "\0", "\0");
    return new_t;
}

text* concat_text(text* arg1, text* arg2)
{
    int32 arg1_size = VARSIZE(arg1) - VARHDRSZ;
    int32 arg2_size = VARSIZE(arg2) - VARHDRSZ;
    int32 new_text_size = arg1_size + arg2_size + VARHDRSZ;
    text* new_text = (text*)palloc(new_text_size);
    errno_t errorno = EOK;

    SET_VARSIZE(new_text, new_text_size);
    errorno = memcpy_s(VARDATA(new_text), arg1_size, VARDATA(arg1), arg1_size);
    securec_check(errorno, "\0", "\0");
    errorno = memcpy_s(VARDATA(new_text) + arg1_size, arg2_size, VARDATA(arg2), arg2_size);
    securec_check(errorno, "\0", "\0");

    return new_text;
}

/* Composite types */
bool c_overpaid(HeapTupleHeader t, /* the current instance of EMP */
    int32 limit)
{
    bool isnull = false;
    int32 salary;

    salary = DatumGetInt32(GetAttributeByName(t, "salary", &isnull));
    if (isnull) {
        return false;
    }
    return salary > limit;
}


{
    bool isnull = false;
    int32 salary;

    salary = DatumGetInt32(GetAttributeByName(t, "salary", &isnull));
    if (isnull) {
        return false;
    }
    return salary > limit;
}

/* src/common/tutorial/funcs.cpp */

/******************************************************************************
  These are user-defined functions that can be bound to a openGauss backend
  and called by openGauss to execute SQL functions of the same name.

  The calling format for these functions is defined by the CREATE FUNCTION
  SQL statement that binds them to the backend.

  NOTE: this file shows examples of "old style" function call conventions.
  See funcs_new.c for examples of "new style".
*****************************************************************************/

#include "postgres.h"
#include "knl/knl_variable.h" /* general openGauss declarations */

#include "executor/executor.h" /* for GetAttributeByName() */
#include "utils/geo_decls.h"   /* for point type */

PG_MODULE_MAGIC;

/* These prototypes just prevent possible warnings from gcc. */

int add_one(int arg);
float8* add_one_float8(float8* arg);
Point* makepoint(Point* pointx, Point* pointy);
text* copytext(text* t);
text* concat_text(text* arg1, text* arg2);
bool c_overpaid(HeapTupleHeader t, /* the current instance of EMP */
    int32 limit);

/* By Value */
int add_one(int arg)
{
    return arg + 1;
}

/* By Reference, Fixed Length */
float8* add_one_float8(float8* arg)
{
    float8* result = (float8*)palloc(sizeof(float8));

    *result = *arg + 1.0;

    return result;
}

Point* makepoint(Point* pointx, Point* pointy)
{
    Point* new_point = (Point*)palloc(sizeof(Point));

    new_point->x = pointx->x;
    new_point->y = pointy->y;

    return new_point;
}

/* By Reference, Variable Length */
text* copytext(text* t)
{
    /*
     * VARSIZE is the total size of the struct in bytes.
     */
    text* new_t = (text*)palloc(VARSIZE(t));

    SET_VARSIZE(new_t, VARSIZE(t));

    /*
     * VARDATA is a pointer to the data region of the struct.
     */
    errno_t errorno = EOK;
    errorno = memcpy_s((void *) VARDATA(new_t), /* destination */
        VARSIZE(t) - VARHDRSZ),                 /* how many bytes */
        (void *) VARDATA(t),                    /* source */
        VARSIZE(t) - VARHDRSZ);                 /* how many bytes */
    securec_check(errorno, "\0", "\0");
    return new_t;
}

text* concat_text(text* arg1, text* arg2)
{
    int32 arg1_size = VARSIZE(arg1) - VARHDRSZ;
    int32 arg2_size = VARSIZE(arg2) - VARHDRSZ;
    int32 new_text_size = arg1_size + arg2_size + VARHDRSZ;
    text* new_text = (text*)palloc(new_text_size);
    errno_t errorno = EOK;

    SET_VARSIZE(new_text, new_text_size);
    errorno = memcpy_s(VARDATA(new_text), arg1_size, VARDATA(arg1), arg1_size);
    securec_check(errorno, "\0", "\0");
    errorno = memcpy_s(VARDATA(new_text) + arg1_size, arg2_size, VARDATA(arg2), arg2_size);
    securec_check(errorno, "\0", "\0");

    return new_text;
}

/* Composite types */
bool c_overpaid(HeapTupleHeader t, /* the current instance of EMP */
    int32 limit)


/* src/common/tutorial/funcs.cpp */

/******************************************************************************
  These are user-defined functions that can be bound to a openGauss backend
  and called by openGauss to execute SQL functions of the same name.

  The calling format for these functions is defined by the CREATE FUNCTION
  SQL statement that binds them to the backend.

  NOTE: this file shows examples of "old style" function call conventions.
  See funcs_new.c for examples of "new style".
*****************************************************************************/

#include "postgres.h"
#include "knl/knl_variable.h" /* general openGauss declarations */

#include "executor/executor.h" /* for GetAttributeByName() */
#include "utils/geo_decls.h"   /* for point type */

PG_MODULE_MAGIC;

/* These prototypes just prevent possible warnings from gcc. */

int add_one(int arg);
float8* add_one_float8(float8* arg);
Point* makepoint(Point* pointx, Point* pointy);
text* copytext(text* t);
text* concat_text(text* arg1, text* arg2);
bool c_overpaid(HeapTupleHeader t, /* the current instance of EMP */
    int32 limit);

/* By Value */
int add_one(int arg)
{
    return arg + 1;
}

/* By Reference, Fixed Length */
float8* add_one_float8(float8* arg)
{
    float8* result = (float8*)palloc(sizeof(float8));

    *result = *arg + 1.0;

    return result;
}

Point* makepoint(Point* pointx, Point* pointy)
{
    Point* new_point = (Point*)palloc(sizeof(Point));

    n

    new_point->y = pointy->y;

    return new_point;
}

/* By Reference, Variable Length */
text* copytext(text* t)
{
    /*
     * VARSIZE is the total size of the struct in bytes.
     */
    text* new_t = (text*)palloc(VARSIZE(t));

    SET_VARSIZE(new_t, VARSIZE(t));

    /*
     * VARDATA is a pointer to the data region of the struct.
     */
    errno_t errorno = EOK;
    errorno = memcpy_s((void *) VARDATA(new_t), /* destination */
        VARSIZE(t) - VARHDRSZ),                 /* how many bytes */
        (void *) VARDATA(t),                    /* source */
        VARSIZE(t) - VARHDRSZ);                 /* how many bytes */
    securec_check(errorno, "\0", "\0");
    return new_t;
}

text* concat_text(text* arg1, text* arg2)
{
    int32 arg1_size = VARSIZE(arg1) - VARHDRSZ;
    int32 arg2_size = VARSIZE(arg2) - VARHDRSZ;
    int32 new_text_size = arg1_size + arg2_size + VARHDRSZ;
    text* new_text = (text*)palloc(new_text_size);
    errno_t errorno = EOK;

    SET_VARSIZE(new_text, new_text_size);
    errorno = memcpy_s(VARDATA(new_text), arg1_size, VARDATA(arg1), arg1_size);
    securec_check(errorno, "\0", "\0");
    errorno = memcpy_s(VARDATA(new_text) + arg1_size, arg2_size, VARDATA(arg2), arg2_size);
    securec_check(errorno, "\0", "\0");

    return new_text;
}

/* Composite types */
bool c_overpaid(HeapTupleHeader t, /* the current instance of EMP */
    int32 limit)
{
    bool isnull = false;
    int32 salary;

    salary = DatumGetInt32(GetAttributeByName(t, "salary", &isnull));
    if (isnull) {
        return false;
    }
    return salary > limit;
}


bool c_overpaid(HeapTupleHeader t, /* the current instance of EMP */
    int32 limit)
{
    bool isnull = false;
    int32 salary;

    salary = DatumGetInt32(GetAttributeByName(t, "salary", &isnull));
    if (isnull) {
        return false;
    }
    return salary > limit;
}

/* src/common/tutorial/funcs.cpp */

/******************************************************************************
  These are user-defined functions that can be bound to a openGauss backend
  and called by openGauss to execute SQL functions of the same name.

  The calling format for these functions is defined by the CREATE FUNCTION
  SQL statement that binds them to the backend.

  NOTE: this file shows examples of "old style" function call conventions.
  See funcs_new.c for examples of "new style".
*****************************************************************************/

#include "postgres.h"
#include "knl/knl_variable.h" /* general openGauss declarations */

#include "executor/executor.h" /* for GetAttributeByName() */
#include "utils/geo_decls.h"   /* for point type */

PG_MODULE_MAGIC;

/* These prototypes just prevent possible warnings from gcc. */

int add_one(int arg);
float8* add_one_float8(float8* arg);
Point* makepoint(Point* pointx, Point* pointy);
text* copytext(text* t);
text* concat_text(text* arg1, text* arg2);
bool c_overpaid(HeapTupleHeader t, /* the current instance of EMP */
    int32 limit);

/* By Value */
int add_one(int arg)
{
    return arg + 1;
}

/* By Reference, Fixed Length */
float8* add_one_float8(float8* arg)
{
    float8* result = (float8*)palloc(sizeof(float8));

    *result = *arg + 1.0;

    return result;
}

Point* makepoint(Point* pointx, Point* pointy)
{
    Point* new_point = (Point*)palloc(sizeof(Point));

    new_point->x = pointx->x;
    new_point->y = pointy->y;

    return new_point;
}

/* By Reference, Variable Length */
text* copytext(text* t)
{
    /*
     * VARSIZE is the total size of the struct in bytes.
     */
    text* new_t = (text*)palloc(VARSIZE(t));

    SET_VARSIZE(new_t, VARSIZE(t));

    /*
     * VARDATA is a pointer to the data region of the struct.
     */
    errno_t errorno = EOK;
    errorno = memcpy_s((void *) VARDATA(new_t), /* destination */
        VARSIZE(t) - VARHDRSZ),                 /* how many bytes */
        (void *) VARDATA(t),                    /* source */
        VARSIZE(t) - VARHDRSZ);                 /* how many bytes */
    securec_check(errorno, "\0", "\0");
    return new_t;
}

text* concat_text(text* arg1, text* arg2)
{
    int32 arg1_size = VARSIZE(arg1) - VARHDRSZ;
    int32 arg2_size = VARSIZE(arg2) - VARHDRSZ;
    int32 new_text_size = arg1_size + arg2_size + VARHDRSZ;
    text* new_text = (text*)palloc(new_text_size);
    errno_t errorno = EOK;

    SET_VARSIZE(new_text, new_text_size);
    errorno = memcpy_s(VARDATA(new_text), arg1_size, VARDATA(arg1), arg1_size);
    securec_check(errorno, "\0", "\0");
    errorno = memcpy_s(VARDATA(new_text) + arg1_size, arg2_size, VARDATA(arg2), arg2_size);
    securec_check(errorno, "\0", "\0");

    return new_text;
}

/* Composite types */


#include <PriorityInversion.h>
#include <IceUtil/Thread.h>
#include <IceUtil/Shared.h>
#include <IceUtil/Mutex.h>
#include <IceUtil/Monitor.h>
#include <IceUtil/RecMutex.h>

#include <sstream>
#include <TestHelper.h>
#include <vector>
#include <map>

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace std;
using namespace IceUtil;

class TaskCollector : public IceUtil::Shared
{
public:

    TaskCollector(int cores, int high, int medium, int low, Monitor<Mutex>& monitor) :
        _lowBegin(0),
        _lowEnd(0),
        _mediumBegin(0),
        _mediumEnd(0),
        _highBegin(0),
        _cores(cores),
        _high(high),
        _medium(medium),
        _low(low),
        _acquired(0),
        _monitor(monitor)
    {
    }

    void waitAcquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        while(_acquired == 0)
        {
            _monitor.wait();
        }
    }

    void acquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        ++_acquired;
        _monitor.notifyAll();
    }

{
        Monitor<Mutex>::Lock lock(_monitor);
        while(_mediumBegin < _cores || _highBegin  == 0)
        {
            //Wait until all task are ready to compete by processors
            _monitor.wait();
        }
    }

    void taskBegin(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        if(priority == _low)
        {
            _lowBegin++;
        }
        else if(priority == _medium)
        {
            _mediumBegin++;
        }
        else if(priority == _high)
        {
            _highBegin++;
        }
        _monitor.notifyAll();
    }

    void taskEnd(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        // Test all task begin run before any task ends.
        test(_lowBegin == 1);
        test(_highBegin == 1);
        test(_mediumBegin == _cores);
        if(priority == _low)
        {
            // Low priority thread should end before all medium priority threads.
            test(_mediumEnd == 0);
            _lowEnd++;
        }
        else if(priority == _medium)
        {
            // When the first medium priority task end the
            // low priority task completed.
            test(_lowEnd > 0);
            _mediumEnd++;
        }
    }

private:

    int _lowBegin;
    int _lowEnd;
    int _mediumBegin;
    int _mediumEnd;
    int _highBegin;
    int _cores;
    int _high;
    int _medium;
    int _low;
    int _acquired;
    Monitor<Mutex>& _monitor;
    IceUtil::Mutex _mutex;
};
typedef IceUtil::Handle<TaskCollector> TaskCollectorPtr;

class SharedResource : public IceUtil::Shared
{
public:

    SharedResource(const TaskCollectorPtr& taskCollector) :
        _taskCollector(taskCollector)
    {
    }

    TaskCollectorPtr taskCollector() const { return _taskCollector; }

    virtual void run(int priority) = 0;

private:

    TaskCollectorPtr _taskCollector;
};
typedef IceUtil::Handle<SharedResource> SharedResourcePtr;

class SharedResourceMutex : public SharedResource
{
public:

    SharedResourceMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    virtual void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        Mutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::Mutex _mutex;
};

class SharedResourceRecMutex : public SharedResource
{
public:

    SharedResourceRecMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        RecMutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::RecMutex _mutex;
};

class ThreadCommon : public IceUtil::Thread
{
public:

    virtual void run() = 0;
    int getPriority()
    {
#ifdef _WIN32_WCE
        return CeGetThreadPriority(GetCurrentThread());
#elif defined _WIN32
        return GetThreadPriority(GetCurrentThread());
#else
        sched_param param;
        int sched_policy;
        pthread_t thread = pthread_self();
        pthread_getschedparam(thread, &sched_policy, &param);
        return param.sched_priority;
#endif
    }
};

class Task : public ThreadCommon
{
public:

    Task(const SharedResourcePtr& shared) :
        _shared(shared)
    {
    }

    virtual void run()
    {
        _shared->run(getPriority());
    }

    void waitAcquired()
    {
        _shared->taskCollector()->waitAcquired();
    }

private:

    SharedResourcePtr _shared;
};
typedef IceUtil::Handle<Task> TaskPtr;

class MediumPriorityThread : public ThreadCommon
{
public:

    MediumPriorityThread(const TaskCollectorPtr& taskCollector, const ThreadPtr& highPriorityThread, int timeout) :
        _taskCollector(taskCollector),
        _highPriorityThread(highPriorityThread),
        _timeout(IceUtil::Time::seconds(timeout))
    {
    }

    virtual void run()
    {
        IceUtil::Time timestamp = IceUtil::Time::now(IceUtil::Time::Monotonic);
        _taskCollector->taskBegin(getPriority());
        while(true)
        {
            if(IceUtil::Time::now(IceUtil::Time::Monotonic) - timestamp > _timeout)
            {
                // If high priority task do not end with the specific timeout means
                // that the low priority task priority was not bosted so we are having
                // the clasic priority inversion issue.
                test(false);
            }
            if(!_highPriorityThread->isAlive())
            {
                break;
            }
        }
        _taskCollector->taskEnd(getPriority());
    }

private:

    const TaskCollectorPtr _taskCollector;
    const ThreadPtr _highPriorityThread;
    const IceUtil::Time _timeout;
};

static const string priorityTestName("priority inversion");

PriorityInversionTest::PriorityInversionTest() :
    TestBase(priorityTestName)
{
}

void
PriorityInversionTest::run()
{

#ifdef _WIN32
    return; //Priority inversion is not supported by WIN32
#else
    int cores, high, medium, low, timeout;
    timeout = 30;
    try
    {
        IceUtil::Mutex m;
    }
    catch(const IceUtil::ThreadSyscallException&)
    {
        return; // Mutex protocol PrioInherit not supported
    }
    cores = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
    high = 45;
    medium = 35;
    low = 1;

    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);
        vector<ThreadControl> threads;

        SharedResourcePtr shared = new SharedResourceMutex(collector);

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread
        TaskPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority thread per core.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }
        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }

    // Same test with a recursive mutex.
    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);

        SharedResourcePtr shared = new SharedResourceRecMutex(collector);

        vector<ThreadControl> threads;

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread.
        ThreadPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority tasks per core that runs until
        // the high priority thread is running.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }

        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }
#endif
}


{
        Monitor<Mutex>::Lock lock(_monitor);
        if(priority == _low)
        {
            _lowBegin++;
        }
        else if(priority == _medium)
        {
            _mediumBegin++;
        }
        else if(priority == _high)
        {
            _highBegin++;
        }
        _monitor.notifyAll();
    }

#include <PriorityInversion.h>
#include <IceUtil/Thread.h>
#include <IceUtil/Shared.h>
#include <IceUtil/Mutex.h>
#include <IceUtil/Monitor.h>
#include <IceUtil/RecMutex.h>

#include <sstream>
#include <TestHelper.h>
#include <vector>
#include <map>

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace std;
using namespace IceUtil;

class TaskCollector : public IceUtil::Shared
{
public:

    TaskCollector(int cores, int high, int medium, int low, Monitor<Mutex>& monitor) :
        _lowBegin(0),
        _lowEnd(0),
        _mediumBegin(0),
        _mediumEnd(0),
        _highBegin(0),
        _cores(cores),
        _high(high),
        _medium(medium),
        _low(low),
        _acquired(0),
        _monitor(monitor)
    {
    }

    void waitAcquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        while(_acquired == 0)
        {
            _monitor.wait();
        }
    }

    void acquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        ++_acquired;
        _monitor.notifyAll();
    }

    void waitAll()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        while(_mediumBegin < _cores || _highBegin  == 0)
        {
            //Wait until all task are ready to compete by processors
            _monitor.wait();
        }
    }

    void taskBegin(int priority)

    void taskEnd(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        // Test all task begin run before any task ends.
        test(_lowBegin == 1);
        test(_highBegin == 1);
        test(_mediumBegin == _cores);
        if(priority == _low)
        {
            // Low priority thread should end before all medium priority threads.
            test(_mediumEnd == 0);
            _lowEnd++;
        }
        else if(priority == _medium)
        {
            // When the first medium priority task end the
            // low priority task completed.
            test(_lowEnd > 0);
            _mediumEnd++;
        }
    }

private:

    int _lowBegin;
    int _lowEnd;
    int _mediumBegin;
    int _mediumEnd;
    int _highBegin;
    int _cores;
    int _high;
    int _medium;
    int _low;
    int _acquired;
    Monitor<Mutex>& _monitor;
    IceUtil::Mutex _mutex;
};
typedef IceUtil::Handle<TaskCollector> TaskCollectorPtr;

class SharedResource : public IceUtil::Shared
{
public:

    SharedResource(const TaskCollectorPtr& taskCollector) :
        _taskCollector(taskCollector)
    {
    }

    TaskCollectorPtr taskCollector() const { return _taskCollector; }

    virtual void run(int priority) = 0;

private:

    TaskCollectorPtr _taskCollector;
};
typedef IceUtil::Handle<SharedResource> SharedResourcePtr;

class SharedResourceMutex : public SharedResource
{
public:

    SharedResourceMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    virtual void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        Mutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::Mutex _mutex;
};

class SharedResourceRecMutex : public SharedResource
{
public:

    SharedResourceRecMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        RecMutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::RecMutex _mutex;
};

class ThreadCommon : public IceUtil::Thread
{
public:

    virtual void run() = 0;
    int getPriority()
    {
#ifdef _WIN32_WCE
        return CeGetThreadPriority(GetCurrentThread());
#elif defined _WIN32
        return GetThreadPriority(GetCurrentThread());
#else
        sched_param param;
        int sched_policy;
        pthread_t thread = pthread_self();
        pthread_getschedparam(thread, &sched_policy, &param);
        return param.sched_priority;
#endif
    }
};

class Task : public ThreadCommon
{
public:

    Task(const SharedResourcePtr& shared) :
        _shared(shared)
    {
    }

    virtual void run()
    {
        _shared->run(getPriority());
    }

    void waitAcquired()
    {
        _shared->taskCollector()->waitAcquired();
    }

private:

    SharedResourcePtr _shared;
};
typedef IceUtil::Handle<Task> TaskPtr;

class MediumPriorityThread : public ThreadCommon
{
public:

    MediumPriorityThread(const TaskCollectorPtr& taskCollector, const ThreadPtr& highPriorityThread, int timeout) :
        _taskCollector(taskCollector),
        _highPriorityThread(highPriorityThread),
        _timeout(IceUtil::Time::seconds(timeout))
    {
    }

    virtual void run()
    {
        IceUtil::Time timestamp = IceUtil::Time::now(IceUtil::Time::Monotonic);
        _taskCollector->taskBegin(getPriority());
        while(true)
        {
            if(IceUtil::Time::now(IceUtil::Time::Monotonic) - timestamp > _timeout)
            {
                // If high priority task do not end with the specific timeout means
                // that the low priority task priority was not bosted so we are having
                // the clasic priority inversion issue.
                test(false);
            }
            if(!_highPriorityThread->isAlive())
            {
                break;
            }
        }
        _taskCollector->taskEnd(getPriority());
    }

private:

    const TaskCollectorPtr _taskCollector;
    const ThreadPtr _highPriorityThread;
    const IceUtil::Time _timeout;
};

static const string priorityTestName("priority inversion");

PriorityInversionTest::PriorityInversionTest() :
    TestBase(priorityTestName)
{
}

void
PriorityInversionTest::run()
{

#ifdef _WIN32
    return; //Priority inversion is not supported by WIN32
#else
    int cores, high, medium, low, timeout;
    timeout = 30;
    try
    {
        IceUtil::Mutex m;
    }
    catch(const IceUtil::ThreadSyscallException&)
    {
        return; // Mutex protocol PrioInherit not supported
    }
    cores = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
    high = 45;
    medium = 35;
    low = 1;

    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);
        vector<ThreadControl> threads;

        SharedResourcePtr shared = new SharedResourceMutex(collector);

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread
        TaskPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority thread per core.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }
        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }

    // Same test with a recursive mutex.
    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);

        SharedResourcePtr shared = new SharedResourceRecMutex(collector);

        vector<ThreadControl> threads;

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread.
        ThreadPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority tasks per core that runs until
        // the high priority thread is running.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }

        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }
#endif
}


#include <PriorityInversion.h>
#include <IceUtil/Thread.h>
#include <IceUtil/Shared.h>
#include <IceUtil/Mutex.h>
#include <IceUtil/Monitor.h>
#include <IceUtil/RecMutex.h>

#include <sstream>
#include <TestHelper.h>
#include <vector>
#include <map>

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace std;
using namespace IceUtil;

class TaskCollector : public IceUtil::Shared
{
public:

    TaskCollector(int cores, int high, int medium, int low, Monitor<Mutex>& monitor) :
        _lowBegin(0),
        _lowEnd(0),
        _mediumBegin(0),
        _mediumEnd(0),
        _highBegin(0),
        _cores(cores),
        _high(high),
        _medium(medium),
        _low(low),
        _acquired(0),
        _monitor(monitor)
    {
    }

    void waitAcquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        while(_acquired == 0)
        {
            _monitor.wait();
        }
    }

    void acquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        ++_acquired;
        _monitor.notifyAll();
    }

    void waitAll()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        while(_mediumBegin < _cores || _highBegin  == 0)
        {
            //Wait until all task are ready to compete by processors
            _monitor.wait();
        }
    }

    void taskBegin(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        if(priority == _low)
        {
            _lowBegin++;
        }
        else if(priority == _medium)
        {
            _mediumBegin++;
        }
        else if(priority == _high)
        {
            _highBegin++;
        }
        _monitor.notifyAll();
    }

    void taskEnd(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        // Test all task begin run before any task ends.
        test(_lowBegin == 1);
        test(_highBegin == 1);
        test(_mediumBegin == _cores);
        if(priority == _low)
        {
            // Low priority thread should end before all medium priority threads.
            test(_mediumEnd == 0);
            _lowEnd++;
        }
        else if(priority == _medium)
        {
            // When the first medium priority task end the
            // low priority task completed.
            test(_lowEnd > 0);
            _mediumEnd++;
        }
    }

private:

    int _lowBegin;
    int _lowEnd;
    int _mediumBegin;
    int _mediumEnd;
    int _highBegin;
    int _cores;
    int _high;
    int _medium;
    int _low;
    int _acquired;
    Monitor<Mutex>& _monitor;
    IceUtil::Mutex _mutex;
};
typedef IceUtil::Handle<TaskCollector> TaskCollectorPtr;

class SharedResource : public IceUtil::Shared
{
public:

    SharedResource(const TaskCollectorPtr& taskCollector) :
        _taskCollector(taskCollector)
    {
    }

    TaskCollectorPtr taskCollector() const { return _taskCollector; }

    virtual void run(int priority) = 0;

private:

    TaskCollectorPtr _taskCollector;
};
typedef IceUtil::Handle<SharedResource> SharedResourcePtr;

class SharedResourceMutex : public SharedResource
{
public:

    SharedResourceMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    virtual void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        Mutex::Lock lock(_mutex);
        taskCollector()->acquired(

        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::Mutex _mutex;
};

class SharedResourceRecMutex : public SharedResource
{
public:

    SharedResourceRecMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        RecMutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::RecMutex _mutex;
};

class ThreadCommon : public IceUtil::Thread
{
public:

    virtual void run() = 0;
    int getPriority()
    {
#ifdef _WIN32_WCE
        return CeGetThreadPriority(GetCurrentThread());
#elif defined _WIN32
        return GetThreadPriority(GetCurrentThread());
#else
        sched_param param;
        int sched_policy;
        pthread_t thread = pthread_self();
        pthread_getschedparam(thread, &sched_policy, &param);
        return param.sched_priority;
#endif
    }
};

class Task : public ThreadCommon
{
public:

    Task(const SharedResourcePtr& shared) :
        _shared(shared)
    {
    }

    virtual void run()
    {
        _shared->run(getPriority());
    }

    void waitAcquired()
    {
        _shared->taskCollector()->waitAcquired();
    }

private:

    SharedResourcePtr _shared;
};
typedef IceUtil::Handle<Task> TaskPtr;

class MediumPriorityThread : public ThreadCommon
{
public:

    MediumPriorityThread(const TaskCollectorPtr& taskCollector, const ThreadPtr& highPriorityThread, int timeout) :
        _taskCollector(taskCollector),
        _highPriorityThread(highPriorityThread),
        _timeout(IceUtil::Time::seconds(timeout))
    {
    }

    virtual void run()
    {
        IceUtil::Time timestamp = IceUtil::Time::now(IceUtil::Time::Monotonic);
        _taskCollector->taskBegin(getPriority());
        while(true)
        {
            if(IceUtil::Time::now(IceUtil::Time::Monotonic) - timestamp > _timeout)
            {
                // If high priority task do not end with the specific timeout means
                // that the low priority task priority was not bosted so we are having
                // the clasic priority inversion issue.
                test(false);
            }
            if(!_highPriorityThread->isAlive())
            {
                break;
            }
        }
        _taskCollector->taskEnd(getPriority());
    }

private:

    const TaskCollectorPtr _taskCollector;
    const ThreadPtr _highPriorityThread;
    const IceUtil::Time _timeout;
};

static const string priorityTestName("priority inversion");

PriorityInversionTest::PriorityInversionTest() :
    TestBase(priorityTestName)
{
}

void
PriorityInversionTest::run()
{

#ifdef _WIN32
    return; //Priority inversion is not supported by WIN32
#else
    int cores, high, medium, low, timeout;
    timeout = 30;
    try
    {
        IceUtil::Mutex m;
    }
    catch(const IceUtil::ThreadSyscallException&)
    {
        return; // Mutex protocol PrioInherit not supported
    }
    cores = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
    high = 45;
    medium = 35;
    low = 1;

    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);
        vector<ThreadControl> threads;

        SharedResourcePtr shared = new SharedResourceMutex(collector);

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread
        TaskPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority thread per core.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }
        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }

    // Same test with a recursive mutex.
    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);

        SharedResourcePtr shared = new SharedResourceRecMutex(collector);

        vector<ThreadControl> threads;

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread.
        ThreadPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority tasks per core that runs until
        // the high priority thread is running.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }

        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }
#endif
}


while(_mediumBegin < _cores || _highBegin  == 0)
        {
            //Wait until all task are ready to compete by processors
            _monitor.wait();
        }

#include <PriorityInversion.h>
#include <IceUtil/Thread.h>
#include <IceUtil/Shared.h>
#include <IceUtil/Mutex.h>
#include <IceUtil/Monitor.h>
#include <IceUtil/RecMutex.h>

#include <sstream>
#include <TestHelper.h>
#include <vector>
#include <map>

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace std;
using namespace IceUtil;

class TaskCollector : public IceUtil::Shared
{
public:

    TaskCollector(int cores, int high, int medium, int low, Monitor<Mutex>& monitor) :
        _lowBegin(0),
        _lowEnd(0),
        _mediumBegin(0),
        _mediumEnd(0),
        _highBegin(0),
        _cores(cores),
        _high(high),
        _medium(medium),
        _low(low),
        _acquired(0),
        _monitor(monitor)
    {
    }

    void waitAcquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        while(_acquired == 0)
        {
            _monitor.wait();
        }
    }

    void acquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        ++_acquired;
        _monitor.notifyAll();
    }

    void waitAll()
    {
        Monitor<Mutex>::Lock lock(_monitor);

    }

    void taskBegin(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        if(priority == _low)
        {
            _lowBegin++;
        }
        else if(priority == _medium)
        {
            _mediumBegin++;
        }
        else if(priority == _high)
        {
            _highBegin++;
        }
        _monitor.notifyAll();
    }

    void taskEnd(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        // Test all task begin run before any task ends.
        test(_lowBegin == 1);
        test(_highBegin == 1);
        test(_mediumBegin == _cores);
        if(priority == _low)
        {
            // Low priority thread should end before all medium priority threads.
            test(_mediumEnd == 0);
            _lowEnd++;
        }
        else if(priority == _medium)
        {
            // When the first medium priority task end the
            // low priority task completed.
            test(_lowEnd > 0);
            _mediumEnd++;
        }
    }

private:

    int _lowBegin;
    int _lowEnd;
    int _mediumBegin;
    int _mediumEnd;
    int _highBegin;
    int _cores;
    int _high;
    int _medium;
    int _low;
    int _acquired;
    Monitor<Mutex>& _monitor;
    IceUtil::Mutex _mutex;
};
typedef IceUtil::Handle<TaskCollector> TaskCollectorPtr;

class SharedResource : public IceUtil::Shared
{
public:

    SharedResource(const TaskCollectorPtr& taskCollector) :
        _taskCollector(taskCollector)
    {
    }

    TaskCollectorPtr taskCollector() const { return _taskCollector; }

    virtual void run(int priority) = 0;

private:

    TaskCollectorPtr _taskCollector;
};
typedef IceUtil::Handle<SharedResource> SharedResourcePtr;

class SharedResourceMutex : public SharedResource
{
public:

    SharedResourceMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    virtual void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        Mutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::Mutex _mutex;
};

class SharedResourceRecMutex : public SharedResource
{
public:

    SharedResourceRecMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        RecMutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::RecMutex _mutex;
};

class ThreadCommon : public IceUtil::Thread
{
public:

    virtual void run() = 0;
    int getPriority()
    {
#ifdef _WIN32_WCE
        return CeGetThreadPriority(GetCurrentThread());
#elif defined _WIN32
        return GetThreadPriority(GetCurrentThread());
#else
        sched_param param;
        int sched_policy;
        pthread_t thread = pthread_self();
        pthread_getschedparam(thread, &sched_policy, &param);
        return param.sched_priority;
#endif
    }
};

class Task : public ThreadCommon
{
public:

    Task(const SharedResourcePtr& shared) :
        _shared(shared)
    {
    }

    virtual void run()
    {
        _shared->run(getPriority());
    }

    void waitAcquired()
    {
        _shared->taskCollector()->waitAcquired();
    }

private:

    SharedResourcePtr _shared;
};
typedef IceUtil::Handle<Task> TaskPtr;

class MediumPriorityThread : public ThreadCommon
{
public:

    MediumPriorityThread(const TaskCollectorPtr& taskCollector, const ThreadPtr& highPriorityThread, int timeout) :
        _taskCollector(taskCollector),
        _highPriorityThread(highPriorityThread),
        _timeout(IceUtil::Time::seconds(timeout))
    {
    }

    virtual void run()
    {
        IceUtil::Time timestamp = IceUtil::Time::now(IceUtil::Time::Monotonic);
        _taskCollector->taskBegin(getPriority());
        while(true)
        {
            if(IceUtil::Time::now(IceUtil::Time::Monotonic) - timestamp > _timeout)
            {
                // If high priority task do not end with the specific timeout means
                // that the low priority task priority was not bosted so we are having
                // the clasic priority inversion issue.
                test(false);
            }
            if(!_highPriorityThread->isAlive())
            {
                break;
            }
        }
        _taskCollector->taskEnd(getPriority());
    }

private:

    const TaskCollectorPtr _taskCollector;
    const ThreadPtr _highPriorityThread;
    const IceUtil::Time _timeout;
};

static const string priorityTestName("priority inversion");

PriorityInversionTest::PriorityInversionTest() :
    TestBase(priorityTestName)
{
}

void
PriorityInversionTest::run()
{

#ifdef _WIN32
    return; //Priority inversion is not supported by WIN32
#else
    int cores, high, medium, low, timeout;
    timeout = 30;
    try
    {
        IceUtil::Mutex m;
    }
    catch(const IceUtil::ThreadSyscallException&)
    {
        return; // Mutex protocol PrioInherit not supported
    }
    cores = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
    high = 45;
    medium = 35;
    low = 1;

    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);
        vector<ThreadControl> threads;

        SharedResourcePtr shared = new SharedResourceMutex(collector);

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread
        TaskPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority thread per core.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }
        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }

    // Same test with a recursive mutex.
    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);

        SharedResourcePtr shared = new SharedResourceRecMutex(collector);

        vector<ThreadControl> threads;

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread.
        ThreadPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority tasks per core that runs until
        // the high priority thread is running.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }

        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }
#endif
}


try
    {
        IceUtil::Mutex m;
    }
    catch(const IceUtil::ThreadSyscallException&)
    {
        return; // Mutex protocol PrioInherit not supported
    }

#include <PriorityInversion.h>
#include <IceUtil/Thread.h>
#include <IceUtil/Shared.h>
#include <IceUtil/Mutex.h>
#include <IceUtil/Monitor.h>
#include <IceUtil/RecMutex.h>

#include <sstream>
#include <TestHelper.h>
#include <vector>
#include <map>

#ifndef _WIN32
#include <unistd.h>
#endif

using namespace std;
using namespace IceUtil;

class TaskCollector : public IceUtil::Shared
{
public:

    TaskCollector(int cores, int high, int medium, int low, Monitor<Mutex>& monitor) :
        _lowBegin(0),
        _lowEnd(0),
        _mediumBegin(0),
        _mediumEnd(0),
        _highBegin(0),
        _cores(cores),
        _high(high),
        _medium(medium),
        _low(low),
        _acquired(0),
        _monitor(monitor)
    {
    }

    void waitAcquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        while(_acquired == 0)
        {
            _monitor.wait();
        }
    }

    void acquired()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        ++_acquired;
        _monitor.notifyAll();
    }

    void waitAll()
    {
        Monitor<Mutex>::Lock lock(_monitor);
        while(_mediumBegin < _cores || _highBegin  == 0)
        {
            //Wait until all task are ready to compete by processors
            _monitor.wait();
        }
    }

    void taskBegin(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        if(priority == _low)
        {
            _lowBegin++;
        }
        else if(priority == _medium)
        {
            _mediumBegin++;
        }
        else if(priority == _high)
        {
            _highBegin++;
        }
        _monitor.notifyAll();
    }

    void taskEnd(int priority)
    {
        Monitor<Mutex>::Lock lock(_monitor);
        // Test all task begin run before any task ends.
        test(_lowBegin == 1);
        test(_highBegin == 1);
        test(_mediumBegin == _cores);
        if(priority == _low)
        {
            // Low priority thread should end before all medium priority threads.
            test(_mediumEnd == 0);
            _lowEnd++;
        }
        else if(priority == _medium)
        {
            // When the first medium priority task end the
            // low priority task completed.
            test(_lowEnd > 0);
            _mediumEnd++;
        }
    }

private:

    int _lowBegin;
    int _lowEnd;
    int _mediumBegin;
    int _mediumEnd;
    int _highBegin;
    int _cores;
    int _high;
    int _medium;
    int _low;
    int _acquired;
    Monitor<Mutex>& _monitor;
    IceUtil::Mutex _mutex;
};
typedef IceUtil::Handle<TaskCollector> TaskCollectorPtr;

class SharedResource : public IceUtil::Shared
{
public:

    SharedResource(const TaskCollectorPtr& taskCollector) :
        _taskCollector(taskCollector)
    {
    }

    TaskCollectorPtr taskCollector() const { return _taskCollector; }

    virtual void run(int priority) = 0;

private:

    TaskCollectorPtr _taskCollector;
};
typedef IceUtil::Handle<SharedResource> SharedResourcePtr;

class SharedResourceMutex : public SharedResource
{
public:

    SharedResourceMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    virtual void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        Mutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::Mutex _mutex;
};

class SharedResourceRecMutex : public SharedResource
{
public:

    SharedResourceRecMutex(const TaskCollectorPtr& taskCollector) :
        SharedResource(taskCollector)
    {
    }

    void run(int priority)
    {
        taskCollector()->taskBegin(priority);
        RecMutex::Lock lock(_mutex);
        taskCollector()->acquired();
        taskCollector()->waitAll();
        // If this is the low priority thread we ensure the test runs at least timeout
        // seconds this ensure that it doesn't terminate righ away and medium priority
        // threads will take over all available cores
        IceUtil::Time t = IceUtil::Time::now(IceUtil::Time::Monotonic);
        IceUtil::Time timeout = IceUtil::Time::seconds(2);
        if(priority == 1)
        {
            while(true)
            {
                if(IceUtil::Time::now(IceUtil::Time::Monotonic) - t > timeout)
                {
                    break;
                }
            }
        }
        taskCollector()->taskEnd(priority);
    }

private:

    IceUtil::RecMutex _mutex;
};

class ThreadCommon : public IceUtil::Thread
{
public:

    virtual void run() = 0;
    int getPriority()
    {
#ifdef _WIN32_WCE
        return CeGetThreadPriority(GetCurrentThread());
#elif defined _WIN32
        return GetThreadPriority(GetCurrentThread());
#else
        sched_param param;
        int sched_policy;
        pthread_t thread = pthread_self();
        pthread_getschedparam(thread, &sched_policy, &param);
        return param.sched_priority;
#endif
    }
};

class Task : public ThreadCommon
{
public:

    Task(const SharedResourcePtr& shared) :
        _shared(shared)
    {
    }

    virtual void run()
    {
        _shared->run(getPriority());
    }

    void waitAcquired()
    {
        _shared->taskCollector()->waitAcquired();
    }

private:

    SharedResourcePtr _shared;
};
typedef IceUtil::Handle<Task> TaskPtr;

class MediumPriorityThread : public ThreadCommon
{
public:

    MediumPriorityThread(const TaskCollectorPtr& taskCollector, const ThreadPtr& highPriorityThread, int timeout) :
        _taskCollector(taskCollector),
        _highPriorityThread(highPriorityThread),
        _timeout(IceUtil::Time::seconds(timeout))
    {
    }

    virtual void run()
    {
        IceUtil::Time timestamp = IceUtil::Time::now(IceUtil::Time::Monotonic);
        _taskCollector->taskBegin(getPriority());
        while(true)
        {
            if(IceUtil::Time::now(IceUtil::Time::Monotonic) - timestamp > _timeout)
            {
                // If high priority task do not end with the specific timeout means
                // that the low priority task priority was not bosted so we are having
                // the clasic priority inversion issue.
                test(false);
            }
            if(!_highPriorityThread->isAlive())
            {
                break;
            }
        }
        _taskCollector->taskEnd(getPriority());
    }

private:

    const TaskCollectorPtr _taskCollector;
    const ThreadPtr _highPriorityThread;
    const IceUtil::Time _timeout;
};

static const string priorityTestName("priority inversion");

PriorityInversionTest::PriorityInversionTest() :
    TestBase(priorityTestName)
{
}

void
PriorityInversionTest::run()
{

#ifdef _WIN32
    return; //Priority inversion is not supported by WIN32
#else
    int cores, high, medium, low, timeout;
    timeout = 30;

    cores = static_cast<int>(sysconf(_SC_NPROCESSORS_ONLN));
    high = 45;
    medium = 35;
    low = 1;

    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);
        vector<ThreadControl> threads;

        SharedResourcePtr shared = new SharedResourceMutex(collector);

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread
        TaskPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority thread per core.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }
        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }

    // Same test with a recursive mutex.
    {
        Monitor<Mutex> monitor;
        TaskCollectorPtr collector = new TaskCollector(cores, high, medium, low, monitor);

        SharedResourcePtr shared = new SharedResourceRecMutex(collector);

        vector<ThreadControl> threads;

        // Create one low priority thread.
        TaskPtr lowThread = new Task(shared);
        threads.push_back(lowThread->start(128, low));
        lowThread->waitAcquired();

        // Create one high priority thread that use the same shared resource
        // as the previous low priority thread.
        ThreadPtr highThread = new Task(shared);
        threads.push_back(highThread->start(128, high));

        // Create one medium priority tasks per core that runs until
        // the high priority thread is running.
        for(int cont = 0; cont < cores; ++cont)
        {
            ThreadPtr t = new MediumPriorityThread(collector, highThread, timeout);
            threads.push_back(t->start(128, medium));
        }

        // Join with all the threads.
        vector<ThreadControl>::iterator it;
        for(it = threads.begin(); it != threads.end(); ++it)
        {
            try
            {
                (*it).join();
            }
            catch(...)
            {
            }
        }
    }
#endif
}


/***************************************************************************

    Konami 005289 - SCC sound as used in Bubblesystem

    This file is pieced together by Bryan McPhail from a combination of
    Namco Sound, Amuse by Cab, Nemesis schematics and whoever first
    figured out SCC!

    The 005289 is a 2 channel sound generator. Each channel gets its
    waveform from a prom (4 bits wide).

    (From Nemesis schematics)

    Address lines A0-A4 of the prom run to the 005289, giving 32 bytes
    per waveform.  Address lines A5-A7 of the prom run to PA5-PA7 of
    the AY8910 control port A, giving 8 different waveforms. PA0-PA3
    of the AY8910 control volume.

    The second channel is the same as above except port B is used.

    The 005289 has 12 address inputs and 4 control inputs: LD1, LD2, TG1, TG2.
    It has no data bus, so data values written don't matter.
    When LD1 or LD2 is asserted, the 12 bit value on the address bus is
    latched. Each of the two channels has its own latch.
    When TG1 or TG2 is asserted, the frequency of the respective channel is
    set to the previously latched value.

    The 005289 itself is nothing but an address generator. Digital to analog
    conversion, volume control and mixing of the channels is all done
    externally via resistor networks and 4066 switches and is only implemented
    here for convenience.

    Ported from MAME SVN 27/05/2014

***************************************************************************/

#include "burnint.h"
#include "k005289.h"

// is this an actual hardware limit? or just an arbitrary divider
// to bring the output frequency down to a reasonable value for MAME?
#define CLOCK_DIVIDER 32

static const UINT8 *sound_prom;
static INT32 rate;

static INT16 *mixer_table;
static INT16 *mixer_lookup;
static INT16 *mixer_buffer;
static double gain[2];
static INT32  output_dir[2];

static UINT32 counter[2];
static UINT16 frequency[2];
static UINT16 freq_latch[2];
static UINT16 waveform[2];
static UINT8 volume[2];

/* build a table to divide by the number of voices */
static void make_mixer_table(INT32 voices)
{
	INT32 count = voices * 128;
	INT32 i;
	INT32 ngain = 16;

	/* allocate memory */
	mixer_table = (INT16*)BurnMalloc(256 * voices * sizeof(INT16));

	/* find the middle of the table */
	mixer_lookup = mixer_table + (128 * voices);

	/* fill in the table - 16 bit case */
	for (i = 0; i < count; i++)
	{
		INT32 val = i * ngain * 16 / voices;
		if (val > 32767) val = 32767;
		mixer_lookup[ i] = val;
		mixer_lookup[-i] = -val;
	}
}

void K005289Reset()
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Reset called without init\n"));
#endif

	/* reset all the voices */
	for (INT32 i = 0; i < 2; i++)
	{
		counter[i] = 0;
		frequency[i] = 0;
		freq_latch[i] = 0;
		waveform[i] = i * 0x100;
		volume[i] = 0;
	}
}

void K005289Init(INT32 clock, UINT8 *prom)
{
	/* get stream channels */
	rate = ((clock / CLOCK_DIVIDER) * 100) / nBurnFPS;

	/* allocate a pair of buffers to mix into - 1 frame's worth should be more than enough */
	mixer_buffer = (INT16*)BurnMalloc(rate * sizeof(INT16));

	/* build the mixer table */
	make_mixer_table(2);

	sound_prom = prom;

	DebugSnd_K005289Initted = 1;
}

void K005289SetRoute(INT32 nIndex, double nVolume, INT32 nRouteDir)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289SetRoute called without init\n"));
#endif

	gain[nIndex] = nVolume;
	output_dir[nIndex] = nRouteDir;
}

void K005289Exit()
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Exit called without init\n"));
#endif

	if (!DebugSnd_K005289Initted) return;

	BurnFree (mixer_buffer);
	BurnFree (mixer_table);
	mixer_buffer = NULL;
	mixer_table = NULL;

	DebugSnd_K005289Initted = 0;
}

void K005289Update(INT16 *buffer, INT32 samples)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Update called without init\n"));
#endif

	INT16 *mix;
	INT32 i,v,f;

	/* zap the contents of the mixer buffer */
	memset(mixer_buffer, 0, rate * sizeof(INT16));

	v=volume[0];
	f=frequency[0];
	if (v && f)
	{
		const UINT8 *w = sound_prom + waveform[0];
		INT32 c = counter[0];

		mix = mixer_buffer;

		/* add our contribution */
		for (i = 0; i < rate; i++)
		{
			INT32 offs;

			c += CLOCK_DIVIDER;
			offs = (c / f) & 0x1f;
			*mix++ += ((w[offs] & 0x0f) - 8) * v;
		}

		/* update the counter for this voice */
		counter[0] = c % (f * 0x20);
	}

	v=volume[1];
	f=frequency[1];
	if (v && f)
	{
		const UINT8 *w = sound_prom + waveform[1];
		INT32 c = counter[1];

		mix = mixer_buffer;

		/* add our contribution */
		for (i = 0; i < rate; i++)
		{
			INT32 offs;

			c += CLOCK_DIVIDER;
			offs = (c / f) & 0x1f;
			*mix++ += ((w[offs] & 0x0f) - 8) * v;
		}

		/* update the counter for this voice */
		counter[1] = c % (f * 0x20);
	}

	/* mix it down */
	mix = mixer_buffer;
	for (i = 0; i < samples; i++)
	{
		INT32 nLeftSample = mixer_lookup[mix[(i * rate) / nBurnSoundLen]];
		INT32 nRightSample = nLeftSample;

		if ((output_dir[BURN_SND_K005289_ROUTE_1] & BURN_SND_ROUTE_LEFT) == BURN_SND_ROUTE_LEFT) {
			nLeftSample = (INT32)(nLeftSample * gain[BURN_SND_K005289_ROUTE_1]);
		}
		if ((output_dir[BURN_SND_K005289_ROUTE_1] & BURN_SND_ROUTE_RIGHT) == BURN_SND_ROUTE_RIGHT) {
			nRightSample = (INT32)(nRightSample * gain[BURN_SND_K005289_ROUTE_1]);
		}

		nLeftSample = BURN_SND_CLIP(nLeftSample);
		nRightSample = BURN_SND_CLIP(nRightSample);

		buffer[0] = BURN_SND_CLIP(buffer[0] + nLeftSample);
		buffer[1] = BURN_SND_CLIP(buffer[1] + nRightSample);
		buffer+=2;
	}
}

void K005289ControlAWrite(UINT8 data)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289ControlAWrite called without init\n"));
#endif

	volume[0] = data & 0xf;
	waveform[0] = data & 0xe0;
}

void K005289ControlBWrite(UINT8 data)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289ControlBWrite called without init\n"));
#endif

	volume[1] = data & 0xf;
	waveform[1] = (data & 0xe0) + 0x100;
}

void K005289Ld1Write(INT32 offset)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Ld1 called without init\n"));
#endif

	offset &= 0xfff;
	freq_latch[0] = 0xfff - offset;
}

void K005289Ld2Write(INT32 offset)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Ld2 called without init\n"));
#endif

	offset &= 0xfff;
	freq_latch[1] = 0xfff - offset;
}

{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Tg1 called without init\n"));
#endif

	frequency[0] = freq_latch[0];
}

void K005289Tg2Write()
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Tg2 called without init\n"));
#endif

	frequency[1] = freq_latch[1];
}

void K005289Scan(INT32 nAction, INT32 *)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Scan called without init\n"));
#endif

	if (nAction & ACB_DRIVER_DATA)
	{
		for (INT32 i = 0; i < 2; i++) {
			SCAN_VAR(counter[i]);
			SCAN_VAR(frequency[i]);
			SCAN_VAR(freq_latch[i]);
			SCAN_VAR(waveform[i]);
			SCAN_VAR(volume[i]);
		}
	}
}


{
	/* get stream channels */
	rate = ((clock / CLOCK_DIVIDER) * 100) / nBurnFPS;

	/* allocate a pair of buffers to mix into - 1 frame's worth should be more than enough */
	mixer_buffer = (INT16*)BurnMalloc(rate * sizeof(INT16));

	/* build the mixer table */
	make_mixer_table(2);

	sound_prom = prom;

	DebugSnd_K005289Initted = 1;
}

/***************************************************************************

    Konami 005289 - SCC sound as used in Bubblesystem

    This file is pieced together by Bryan McPhail from a combination of
    Namco Sound, Amuse by Cab, Nemesis schematics and whoever first
    figured out SCC!

    The 005289 is a 2 channel sound generator. Each channel gets its
    waveform from a prom (4 bits wide).

    (From Nemesis schematics)

    Address lines A0-A4 of the prom run to the 005289, giving 32 bytes
    per waveform.  Address lines A5-A7 of the prom run to PA5-PA7 of
    the AY8910 control port A, giving 8 different waveforms. PA0-PA3
    of the AY8910 control volume.

    The second channel is the same as above except port B is used.

    The 005289 has 12 address inputs and 4 control inputs: LD1, LD2, TG1, TG2.
    It has no data bus, so data values written don't matter.
    When LD1 or LD2 is asserted, the 12 bit value on the address bus is
    latched. Each of the two channels has its own latch.
    When TG1 or TG2 is asserted, the frequency of the respective channel is
    set to the previously latched value.

    The 005289 itself is nothing but an address generator. Digital to analog
    conversion, volume control and mixing of the channels is all done
    externally via resistor networks and 4066 switches and is only implemented
    here for convenience.

    Ported from MAME SVN 27/05/2014

***************************************************************************/

#include "burnint.h"
#include "k005289.h"

// is this an actual hardware limit? or just an arbitrary divider
// to bring the output frequency down to a reasonable value for MAME?
#define CLOCK_DIVIDER 32

static const UINT8 *sound_prom;
static INT32 rate;

static INT16 *mixer_table;
static INT16 *mixer_lookup;
static INT16 *mixer_buffer;
static double gain[2];
static INT32  output_dir[2];

static UINT32 counter[2];
static UINT16 frequency[2];
static UINT16 freq_latch[2];
static UINT16 waveform[2];
static UINT8 volume[2];

/* build a table to divide by the number of voices */
static void make_mixer_table(INT32 voices)
{
	INT32 count = voices * 128;
	INT32 i;
	INT32 ngain = 16;

	/* allocate memory */
	mixer_table = (INT16*)BurnMalloc(256 * voices * sizeof(INT16));

	/* find the middle of the table */
	mixer_lookup = mixer_table + (128 * voices);

	/* fill in the table - 16 bit case */
	for (i = 0; i < count; i++)
	{
		INT32 val = i * ngain * 16 / voices;
		if (val > 32767) val = 32767;
		mixer_lookup[ i] = val;
		mixer_lookup[-i] = -val;
	}
}

void K005289Reset()
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Reset called without init\n"));
#endif

	/* reset all the voices */
	for (INT32 i = 0; i < 2; i++)
	{
		counter[i] = 0;
		frequency[i] = 0;
		freq_latch[i] = 0;
		waveform[i] = i * 0x100;
		volume[i] = 0;
	}
}

void K005289Init(INT32 clock, UINT8 *prom)

void K005289SetRoute(INT32 nIndex, double nVolume, INT32 nRouteDir)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289SetRoute called without init\n"));
#endif

	gain[nIndex] = nVolume;
	output_dir[nIndex] = nRouteDir;
}

void K005289Exit()
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Exit called without init\n"));
#endif

	if (!DebugSnd_K005289Initted) return;

	BurnFree (mixer_buffer);
	BurnFree (mixer_table);
	mixer_buffer = NULL;
	mixer_table = NULL;

	DebugSnd_K005289Initted = 0;
}

void K005289Update(INT16 *buffer, INT32 samples)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Update called without init\n"));
#endif

	INT16 *mix;
	INT32 i,v,f;

	/* zap the contents of the mixer buffer */
	memset(mixer_buffer, 0, rate * sizeof(INT16));

	v=volume[0];
	f=frequency[0];
	if (v && f)
	{
		const UINT8 *w = sound_prom + waveform[0];
		INT32 c = counter[0];

		mix = mixer_buffer;

		/* add our contribution */
		for (i = 0; i < rate; i++)
		{
			INT32 offs;

			c += CLOCK_DIVIDER;
			offs = (c / f) & 0x1f;
			*mix++ += ((w[offs] & 0x0f) - 8) * v;
		}

		/* update the counter for this voice */
		counter[0] = c % (f * 0x20);
	}

	v=volume[1];
	f=frequency[1];
	if (v && f)
	{
		const UINT8 *w = sound_prom + waveform[1];
		INT32 c = counter[1];

		mix = mixer_buffer;

		/* add our contribution */
		for (i = 0; i < rate; i++)
		{
			INT32 offs;

			c += CLOCK_DIVIDER;
			offs = (c / f) & 0x1f;
			*mix++ += ((w[offs] & 0x0f) - 8) * v;
		}

		/* update the counter for this voice */
		counter[1] = c % (f * 0x20);
	}

	/* mix it down */
	mix = mixer_buffer;
	for (i = 0; i < samples; i++)
	{
		INT32 nLeftSample = mixer_lookup[mix[(i * rate) / nBurnSoundLen]];
		INT32 nRightSample = nLeftSample;

		if ((output_dir[BURN_SND_K005289_ROUTE_1] & BURN_SND_ROUTE_LEFT) == BURN_SND_ROUTE_LEFT) {
			nLeftSample = (INT32)(nLeftSample * gain[BURN_SND_K005289_ROUTE_1]);
		}
		if ((output_dir[BURN_SND_K005289_ROUTE_1] & BURN_SND_ROUTE_RIGHT) == BURN_SND_ROUTE_RIGHT) {
			nRightSample = (INT32)(nRightSample * gain[BURN_SND_K005289_ROUTE_1]);
		}

		nLeftSample = BURN_SND_CLIP(nLeftSample);
		nRightSample = BURN_SND_CLIP(nRightSample);

		buffer[0] = BURN_SND_CLIP(buffer[0] + nLeftSample);
		buffer[1] = BURN_SND_CLIP(buffer[1] + nRightSample);
		buffer+=2;
	}
}

void K005289ControlAWrite(UINT8 data)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289ControlAWrite called without init\n"));
#endif

	volume[0] = data & 0xf;
	waveform[0] = data & 0xe0;
}

void K005289ControlBWrite(UINT8 data)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289ControlBWrite called without init\n"));
#endif

	volume[1] = data & 0xf;
	waveform[1] = (data & 0xe0) + 0x100;
}

void K005289Ld1Write(INT32 offset)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Ld1 called without init\n"));
#endif

	offset &= 0xfff;
	freq_latch[0] = 0xfff - offset;
}

void K005289Ld2Write(INT32 offset)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Ld2 called without init\n"));
#endif

	offset &= 0xfff;
	freq_latch[1] = 0xfff - offset;
}

void K005289Tg1Write()
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Tg1 called without init\n"));
#endif

	frequency[0] = freq_latch[0];
}

void K005289Tg2Write()
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Tg2 called without init\n"));
#endif

	frequency[1] = freq_latch[1];
}

void K005289Scan(INT32 nAction, INT32 *)
{
#if defined FBA_DEBUG
	if (!DebugSnd_K005289Initted) bprintf(PRINT_ERROR, _T("K005289Scan called without init\n"));
#endif

	if (nAction & ACB_DRIVER_DATA)
	{
		for (INT32 i = 0; i < 2; i++) {
			SCAN_VAR(counter[i]);
			SCAN_VAR(frequency[i]);
			SCAN_VAR(freq_latch[i]);
			SCAN_VAR(waveform[i]);
			SCAN_VAR(volume[i]);
		}
	}
}