/*
    zthread.h - libzia thread functions
    Copyright (C) 2011 Ladislav Vaiz <ok1zia@nagano.cz>

    This program is free software; you can redistribute it and/or
    modify it under the terms of the GNU General Public License
    version 2 as published by the Free Software Foundation.

*/

#ifndef __ZTHREAD_H
#define __ZTHREAD_H

#include <libziaint.h>

#include <glib.h>


#if GLIB_CHECK_VERSION(2, 32, 0)
#define MUTEX_INIT(x) g_mutex_init(&x##_mutex);
#define MUTEX_FREE(x) {}
#else
#define MUTEX_INIT(x) x##_mutex = g_mutex_new()
#define MUTEX_FREE(x) if (x##_mutex) {g_mutex_free(x##_mutex); x##_mutex = NULL;}
#endif

#ifdef Z_LEAK_DEBUG_LIST

#define MUTEX_DEFINE(x) \
    GMutex *x##_mutex; \
    char *x##_file; \
    int x##_line;

#define MUTEX_LOCK(x) { \
    g_mutex_lock(x##_mutex); \
    x##_file = __FILE__; \
    x##_line = __LINE__; \
}

#define MUTEX_TRYLOCK(x) { \
    g_mutex_trylock(x##_mutex); \
    x##_file = __FILE__; \
    x##_line = __LINE__; \
}

#define MUTEX_UNLOCK(x) g_mutex_unlock(x##_mutex)

#elif GLIB_CHECK_VERSION(2, 32, 0)

#define MUTEX_DEFINE(x) GMutex x##_mutex
#define MUTEX_LOCK(x) g_mutex_lock(&(x##_mutex))
#define MUTEX_TRYLOCK(x) g_mutex_trylock(&(x##_mutex))
#define MUTEX_UNLOCK(x) g_mutex_unlock(&(x##_mutex))

#else

#define MUTEX_DEFINE(x) GMutex *x##_mutex
#define MUTEX_LOCK(x) g_mutex_lock(x##_mutex)
#define MUTEX_TRYLOCK(x) g_mutex_trylock(x##_mutex)
#define MUTEX_UNLOCK(x) g_mutex_unlock(x##_mutex)

#endif

#ifdef Z_MSC // _MINGW  error: conflicting types for 'sleep'
unsigned int sleep(unsigned sec);
#endif

#ifdef Z_MSC
unsigned int usleep(unsigned usec);
#endif

#ifndef Z_HAVE_G_THREAD_TRY_NEW
GThread *g_thread_try_new(const gchar *name, GThreadFunc func, gpointer data, GError **error);
#endif
void zg_thread_set_name(char* threadName);


int z_cpu_cores(void);

int zg_thread_set_priority(int priority);


#endif
