[SOLVED] Thread-safe usage of logger

Status
Not open for further replies.

emresel

Full Member level 5
Joined
Feb 12, 2008
Messages
267
Helped
61
Reputation
122
Reaction score
61
Trophy points
1,308
Location
Turkiye
Activity points
2,862
Hi colleagues;
I want to use a logger lib for my application in C. I found this on github, it seems quite fit my purposes. My question, how can i use it thread-safely?
In my application, i have two threads and both uses logger function (to print a file or stderr). Author gives a function for this purpose -log_set_lock(log_LockFn fn)- but i couldn't figure out how to use it?
https://github.com/rxi/log.c/#log_set_locklog_lockfn-fn

Thanks for help
 

I suggest to create another thread for logging/printing purposes only (to a file or stderr) with a FIFO.
This thread would be woken up only when something is in the FIFO. The content of this FIFO would be logged/printed.
Then other threads could write theirs records into that FIFO to make theirs log.
 

Hi,
Thanks for your suggestion.
Meanwhile, i think i have found the solution by myself. Here is the explanation;
- Define a mutex
- Define a function to lock and unlock defined mutex
- Pass mutex pointer to logger library by using log_set_udata().
- Pass function to logger library by log_set_lock().

Hence (if you look at log_log() implementation) each time you call log function, it will call the defined function to make a mutex lock/unlock.
You can test it by manually locking the mutex and calling log_() function. It couldn't print till you manually unlock the defined mutex.

Code:
void locklogger(void *udata, int lock)
{
	if (lock)
	{
		pthread_mutex_lock(udata);
	}
	else
	{
		pthread_mutex_unlock(udata);
	}
}


//in main
pthread_mutex_t loglock= PTHREAD_MUTEX_INITIALIZER;
log_set_udata(&loglock);
log_set_lock(locklogger);
 

Status
Not open for further replies.
Cookies are required to use this site. You must accept them to continue using the site. Learn more…