zoukankan      html  css  js  c++  java
  • 线程相关函数(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
    ", (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

  • 相关阅读:
    HTML5 WEB SQL
    Android-day04
    Android-day03
    Android-day02
    Android-day01
    java.lang.ClassNotFoundException: org.apache.jsp.index_jsp
    事务管理、整合Junit、整合Web、SSH整合
    AOP、AspectJ、JdbcTemplate
    Spring基础
    Hibernate对连接池的支持
  • 原文地址:https://www.cnblogs.com/yongdaimi/p/8267335.html
Copyright © 2011-2022 走看看