what exactly does pthread_mutex_lock() ?

This is a discussion on what exactly does pthread_mutex_lock() ? within the C++ Programming forums, part of the General Programming Boards category; Hi, I read some tutorials but couldn't figure out how mutexes really work. consider this example from http://www.ibm.com/developerworks/library/l-posix2/ Code: #include ...

  1. #1
    Registered User
    Join Date
    Nov 2006
    Posts
    519

    what exactly does pthread_mutex_lock() ?

    Hi,

    I read some tutorials but couldn't figure out how mutexes really work.

    consider this example from http://www.ibm.com/developerworks/library/l-posix2/


    Code:
    #include <pthread.h>
    #include <stdlib.h>
    #include <unistd.h>
    #include <stdio.h>
    
    int myglobal;
    pthread_mutex_t mymutex=PTHREAD_MUTEX_INITIALIZER;
    
    void *thread_function(void *arg) {
      int i,j;
      for ( i=0; i<20; i++ ) {
        pthread_mutex_lock(&mymutex);
        j=myglobal;
        j=j+1;
        printf(".");
        fflush(stdout);
       sleep(1);
        myglobal=j;
        pthread_mutex_unlock(&mymutex);
      }
      return NULL;
    }
    
    int main(void) {
    
      pthread_t mythread;
      int i;
    
      if ( pthread_create( &mythread, NULL, thread_function, NULL) ) {
        printf("error creating thread.");
        abort();
      }
    
      for ( i=0; i<20; i++) {
        pthread_mutex_lock(&mymutex);
        myglobal=myglobal+1;
        pthread_mutex_unlock(&mymutex);
        printf("o");
        fflush(stdout);
        sleep(1);
      }
    
      if ( pthread_join ( mythread, NULL ) ) {
        printf("error joining thread.");
        abort();
      }
    
      printf("\nmyglobal equals &#37;d\n",myglobal);
    
      exit(0);
    
    }
    does the mutex_lock pause all other threads until unlock() ?
    and if so, does one ever need more than one mutexes in a programm?

    Or does the mutex_lock prevent all other threads from reading/writing to a variable?
    And if so, how is the mutex "connected" to the variable what shall be protected/locked?

    Or does lock() something completely else?

    Thank you for a short explanation!

  2. #2
    Captain Crash brewbuck's Avatar
    Join Date
    Mar 2007
    Location
    Portland, OR
    Posts
    7,248
    A locked mutex prevents anybody else from locking the mutex. If any other thread tries to call pthread_mutex_lock() on an already-locked mutex, that thread blocks until the mutex is unlocked.

  3. #3
    Registered User
    Join Date
    Nov 2006
    Posts
    519
    Thx brewbuck, think I got the concept. But how does a programmer 2 years later know that he should lock mutex X before accessing data Y?
    Is proper documentation the only way? That sounds little insecure to me.

Popular pages Recent additions subscribe to a feed

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21