#ifndef PTUNIT_THREADS_H
#define PTUNIT_THREADS_H
#include "ptunit.h"
#if defined(FEATURE_THREADS)
# include <threads.h>
#endif
enum {
ptu_thrd_max = 16
};
struct ptunit_thrd_fixture {
#if defined(FEATURE_THREADS)
thrd_t threads[ptu_thrd_max];
mtx_t lock;
#endif
uint8_t nthreads;
int result[ptu_thrd_max];
};
static inline struct ptunit_result
ptunit_thrd_init(struct ptunit_thrd_fixture *tfix)
{
ptu_ptr(tfix);
memset(tfix, 0, sizeof(*tfix));
#if defined(FEATURE_THREADS)
{
int errcode;
errcode = mtx_init(&tfix->lock, mtx_plain);
ptu_int_eq(errcode, thrd_success);
}
#endif
return ptu_passed();
}
static inline struct ptunit_result
ptunit_thrd_fini(struct ptunit_thrd_fixture *tfix)
{
ptu_ptr(tfix);
#if defined(FEATURE_THREADS)
{
int thrd, errcode[ptu_thrd_max];
for (thrd = 0; thrd < tfix->nthreads; ++thrd)
errcode[thrd] = thrd_join(&tfix->threads[thrd],
&tfix->result[thrd]);
mtx_destroy(&tfix->lock);
for (thrd = 0; thrd < tfix->nthreads; ++thrd)
ptu_int_eq(errcode[thrd], thrd_success);
}
#endif
return ptu_passed();
}
#if defined(FEATURE_THREADS)
static inline struct ptunit_result
ptunit_thrd_create(struct ptunit_thrd_fixture *tfix, int (*worker)(void *),
void *arg)
{
int errcode;
ptu_ptr(tfix);
errcode = thrd_create(&tfix->threads[tfix->nthreads++], worker, arg);
ptu_int_eq(errcode, thrd_success);
return ptu_passed();
}
#endif
static inline struct ptunit_result
ptunit_thrd_lock(struct ptunit_thrd_fixture *tfix)
{
ptu_ptr(tfix);
#if defined(FEATURE_THREADS)
{
int errcode;
errcode = mtx_lock(&tfix->lock);
ptu_int_eq(errcode, thrd_success);
}
#endif
return ptu_passed();
}
static inline struct ptunit_result
ptunit_thrd_unlock(struct ptunit_thrd_fixture *tfix)
{
ptu_ptr(tfix);
#if defined(FEATURE_THREADS)
{
int errcode;
errcode = mtx_unlock(&tfix->lock);
ptu_int_eq(errcode, thrd_success);
}
#endif
return ptu_passed();
}
#endif