Mutexes and Threads

Discussion in 'Programming' started by JoJoModding, May 20, 2016.

  1. Hello
    I stumbled over a piece of code used in a lot of android applications today. The code is the wrapper code which lets you use native-only applications on android. It contains (a lot more then) these two methods, of which I stripped code not needed:
    android_app_setup:
    Code (Text):

    pthread_create(&android_app->thread, &attr, android_app_entry, android_app);

    pthread_mutex_lock(&android_app->mutex);
    while (!android_app->running) {
      pthread_cond_wait(&android_app->cond, &android_app->mutex);
    }
    pthread_mutex_unlock(&android_app->mutex);
     
    android_app_entry:
    Code (Text):

    pthread_mutex_lock(&android_app->mutex);
    android_app->running = 1;
    pthread_cond_broadcast(&android_app->cond);
    pthread_mutex_unlock(&android_app->mutex);
     
    android_app is a struct passed to android_app_setup which is later passed as an argument to the newly created thread.
    I understand this as "lock access to android_app and wait for some member field to change" in android_app_setup
    and as "lock access to android_app and change the member field" in android_app_entry.
    However, the entry method should hang when it wants to lock the mutex because it already is locked by the setup method.
    The setup method should also start looping forever because that field never changes.
    There are no other accesses to the field and it is initialized to 0.

    In spite of what I described above, the code works and the methods eventually complete.
    Source: https://raw.githubusercontent.com/c.../android-native-app/android_native_app_glue.c as well as the current android NDK
    License: http://www.apache.org/licenses/LICENSE-2.0
     
  2. Tux

    Tux

    It's entirely possible for the locking function to act as expected if it knows that the same thread currently holds the lock (pthread mutex do optionally support recursive locking).
     
  3. The call to pthread_cond_wait releases the mutex, and blocks until pthread_cond_broadcast is called. After which the waiting thread will reacquire the mutex and continue execution.

    The documentation could have told you as much.

    This is analogous to Java's wait and notify, where similar behaviour is exhibited.
     
    #3 Rocoty, May 21, 2016
    Last edited: May 21, 2016