+ Post New Thread
Results 1 to 3 of 3
  1. #1
    Full Member level 5
    Points: 3,136, Level: 13
    Achievements:
    7 years registered

    Join Date
    Feb 2008
    Location
    Turkiye
    Posts
    257
    Helped
    59 / 59
    Points
    3,136
    Level
    13

    Thread-safe usage of logger

    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

    •   AltAdvertisment

        
       

  2. #2
    Member level 2
    Points: 306, Level: 3
    Achievements:
    Created Blog entry

    Join Date
    Apr 2018
    Location
    Gdańsk, Poland
    Posts
    49
    Helped
    7 / 7
    Points
    306
    Level
    3
    Blog Entries
    3

    Re: Thread-safe usage of logger

    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.



    •   AltAdvertisment

        
       

  3. #3
    Full Member level 5
    Points: 3,136, Level: 13
    Achievements:
    7 years registered

    Join Date
    Feb 2008
    Location
    Turkiye
    Posts
    257
    Helped
    59 / 59
    Points
    3,136
    Level
    13

    Re: Thread-safe usage of logger

    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);



--[[ ]]--