线程相关函数-pthread_mutex_lock(), pthread_mutex_unlock() 互斥锁

Posted 夜行过客

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程相关函数-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

 

以上是关于线程相关函数-pthread_mutex_lock(), pthread_mutex_unlock() 互斥锁的主要内容,如果未能解决你的问题,请参考以下文章

pthread_mutex_lock 导致死锁

LINUX - pthread_mutex_lock

pthread_mutex_lock 和 pthread_mutex_lock 在另一个线程中

关于 pthread_mutex_lock 的一些问题

pthread_cond_wait 和 pthread_mutex_lock 优先级?

Linux-线程同步之互斥锁