Skip to content

Instantly share code, notes, and snippets.

@wzshare
Last active September 6, 2018 02:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wzshare/0be879415e525ca7b4bbb6a0ce13dd20 to your computer and use it in GitHub Desktop.
Save wzshare/0be879415e525ca7b4bbb6a0ce13dd20 to your computer and use it in GitHub Desktop.
Detects when a mutex is used before it’s initialized.

Use the pthread_once(_:_:) function to ensure that initialization is called before a mutex is used.

static pthread_once_t once = PTHREAD_ONCE_INIT;
static pthread_mutex_t mutex;
void init() {    
    pthread_mutex_init(&mutex, NULL);
}
void performWork() {
    pthread_once(&once, init); // Correct
    pthread_mutex_lock(&mutex);
    // ...
    pthread_mutex_unlock(&mutex);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment