简体   繁体   中英

How waiting thread knows that shared resource is unlocked by another thread?

I'm studying multi threaded application. I'm using mutex for synchronization.

I want to understand how waiting thread come to know that the shared resource locked by another thread is unlocked now?

I need to understood the above in the case of "MUTEX" usage.

All threads in the process share a semaphore if it is globally defined.

Assume we have a writeLogMessage(char*) function that opens a file and writes the given String. Calling this method from multiple threads will cause unwanted (and unpredictable behaviour). Hence you could write a thread-safe wrapper function, that waits for other threads to free the shared resource (the logfile in this case).

sem_t log_mutex;

void writeLogTS(char *logmsg) 
{
  sem_wait(&log_mutex); //suspend the thread if another thread is currently writing to the log file
  writeLogMessage(logmsg);
  sem_wait(&log_mutex); //post the mutex semaphore
}

The function sem_wait will decrease the value of the semaphore if it is greater than 0. However, if the value of the log_mutex is 0, sem_wait will suspend the current threads execution until the value is increased again. Increasing the value is done by sem_wait . Ie the other threads know that the shared resource is available again, if the semaphore's value is greater than 0.

EDIT: To serve as a mutex, the semaphore log_mutex has to be initialised before the threads are started as follows: sem_init(&log_mutex, 0, 1); The second argument is 0 to guarantee that the semaphore is shared between threads and the third argument is the initial value. Cf. http://pubs.opengroup.org/onlinepubs/7908799/xsh/sem_init.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM