rxi / log.c

A simple logging library implemented in C99

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Is this library multithreaded safe?

skyformat99 opened this issue · comments

Is this library multithreaded safe?

If you use proper locking, then yes it would be. Here is an example.

#include <pthread.h>
#include "log.h"

pthread_mutex_t MUTEX_LOG;
void log_lock(bool lock, void *udata);

int main() {
  pthread_mutex_init(&MUTEX_LOG, NULL);
  log_set_lock(log_lock, &MUTEX_LOG);

  /* Insert threaded application code here... */

  pthread_mutex_destroy(&MUTEX_LOG);

  return 0;
}

void log_lock(bool lock, void* udata) {
  pthread_mutex_t *LOCK = (pthread_mutex_t*)(udata);
  if (lock)
    pthread_mutex_lock(LOCK);
  else
    pthread_mutex_unlock(LOCK);
}

thanks.
It would be nice to add this code directly to log.c

Possibly, but locking is an extraordinarily complicated topic, and there is no one-size-fits all approach that would work with a portable library like this. For example, the above example only works in POSIX style operating systems, like Linux, BSD, and macOS, that support NPTL.