DLR-SR / Noise

Modelica library for generating stochastic signals to be included in the Modelica Standard Library
9 stars 11 forks source link

Static variables of ModelicaRandom.c are not thread-safe #45

Closed tbeu closed 9 years ago

tbeu commented 9 years ago

ModelicaRandom.c contains static variables ModelicaRandom_s, ModelicaRandom_p and ModelicaRandom_id but the access to these static variables is not thread-safe. In #1433 I fixed this for ModelicaInternal.c using macros MUTEX_LOCK() and MUTEX_UNLOCK() on posix systems and Windows.

#include "gconstructor.h"

/* The standard way to detect posix is to check _POSIX_VERSION,
 * which is defined in <unistd.h>
 */
#if defined(__unix__) || defined(__linux__) || defined(__APPLE_CC__)
  #include <unistd.h>
#endif

#if !defined(_POSIX_) && defined(_POSIX_VERSION)
  #define _POSIX_ 1
#endif

/* ... */

#if defined(_POSIX_)
#include <pthread.h>
static pthread_mutex_t m = PTHREAD_MUTEX_INITIALIZER;
#define MUTEX_LOCK() pthread_mutex_lock(&m)
#define MUTEX_UNLOCK() pthread_mutex_unlock(&m)
#elif defined(_WIN32) && defined(G_HAS_CONSTRUCTORS)
#include <Windows.h>
static CRITICAL_SECTION cs;
#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA
#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(initializeCS)
#endif
G_DEFINE_CONSTRUCTOR(initializeCS)
static void initializeCS(void) {
    InitializeCriticalSection(&cs);
}
#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA
#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(deleteCS)
#endif
G_DEFINE_DESTRUCTOR(deleteCS)
static void deleteCS(void) {
    DeleteCriticalSection(&cs);
}
#define MUTEX_LOCK() EnterCriticalSection(&cs)
#define MUTEX_UNLOCK() LeaveCriticalSection(&cs)
#else
#define MUTEX_LOCK()
#define MUTEX_UNLOCK()
#endif

This also needs to be applied to ModelicaRandom.c.

akloeckner commented 9 years ago

@tbeu. I'm not 100% sure on how to integrate this. I have tried to do so here: https://github.com/akloeckner/Noise/commits/mutex. However, I get a compile error because "gconstructor.h" was not found. Would you mind checking this?

tbeu commented 9 years ago

Take gconstructor.h from MSL trunk.

akloeckner commented 9 years ago

Thanks. That worked. I'm still not sure, if I have used the Mutex constructs correctly. However, I have opened a pull request #46 for this.