線程相關函數(4)-pthread_mutex_lock(), pthread_mutex_unlock() 互斥鎖


互斥鎖實例:

#include <pthread.h>
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int pthread_mutex_destroy(pthread_mutex_t *mutex);
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
int pthread_mutex_lock(pthread_mutex_t *mutex);
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);

 

示例代碼:

#include <pthread.h>
#include <stdio.h>

#define NLOOP 5000

static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
static int counter;

void *doit(void *);


int main()
{
    pthread_t tidA, tidB;
    pthread_create(&tidA, NULL, doit, NULL);
    pthread_create(&tidB, NULL, doit, NULL);

    /*wait for both threads to terminate*/
    pthread_join(tidA, NULL);
    pthread_join(tidB, NULL);
    
    return 0;
}


void *doit(void *arg)
{    
    int i, val;
    for (i=0; i<NLOOP; i++) {
        pthread_mutex_lock(&counter_mutex);
        val = counter;
        printf("%x: %d\n", (unsigned int)pthread_self(), val+1);
        counter = val + 1;
        pthread_mutex_unlock(&counter_mutex);
    }
    return NULL;
}

運行結果:

....

71025700: 9979
71025700: 9980
71025700: 9981
71025700: 9982
71025700: 9983
71025700: 9984
71025700: 9985
71025700: 9986
71025700: 9987
71025700: 9988
71025700: 9989
71025700: 9990
71025700: 9991
71025700: 9992
71025700: 9993
71025700: 9994
71025700: 9995
71025700: 9996
71025700: 9997
71025700: 9998
71025700: 9999
71025700: 10000

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM