Continue to Site

Welcome to EDAboard.com

Welcome to our site! EDAboard.com is an international Electronics Discussion Forum focused on EDA software, circuits, schematics, books, theory, papers, asic, pld, 8051, DSP, Network, RF, Analog Design, PCB, Service Manuals... and a whole lot more! To participate you need to register. Registration is free. Click here to register now.

[SOLVED] Thread-safe usage of logger

Status
Not open for further replies.

emresel

Full Member level 5
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,863
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
log_set_lock(log_LockFn fn)

If the log will be written to from multiple threads a lock function can be set. The function is passed a udata value (set by log_set_udata()) and the integer 1 if the lock should be acquired or 0 if the lock should be released.

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.

Part and Inventory Search

Welcome to EDABoard.com

Sponsor

Back
Top