线程mutex总结和使用

1.mutex常见的类型
1.1 pthread_mutex_t

/* Mutexes (not abstract because of PTHREAD_MUTEX_INITIALIZER).  */
/* (The layout is unnatural to maintain binary compatibility
    with earlier releases of LinuxThreads.) */
typedef struct
{
  int __m_reserved;               /* Reserved for future use */
  int __m_count;                  /* Depth of recursive locking */
  _pthread_descr __m_owner;       /* Owner thread (if recursive or errcheck) */
  int __m_kind;                   /* Mutex kind: fast, recursive or errcheck */
  struct _pthread_fastlock __m_lock; /* Underlying fast lock */
} pthread_mutex_t;



1.2 timespec
struct timespec {
__kernel_time_t tv_sec;                 /* seconds */
long            tv_nsec;                /* nanoseconds */
};




2.mutex常见的函数
  常见函数有:pthread_mutex_init、pthread_mutex_destory、pthread_mutex_trylock、
pthread_mutex_lock、pthread_mutex_timedlock、pthread_mutex_unlock等。
2.1 pthread_mutex_init
头文件:#include <pthread.h>
函数:int pthread_mutex_init(pthread_mutex_t * __mutex,
const pthread_mutexattr_t * __mutex_attr);
功能:Initialize MUTEX using attributes in *MUTEX_ATTR, or use the
   default values if later is NULL. 


2.2 pthread_mutex_destory
头文件:#include <pthread.h>
函数:int pthread_mutex_destroy(pthread_mutex_t * __mutex);
功能:Try to lock MUTEX.


2.3 pthread_mutex_trylock
头文件:#include <pthread.h>
函数:int pthread_mutex_trylock(pthread_mutex_t * __mutex);
功能: Try to lock MUTEX.


2.4 pthread_mutex_lock
头文件:#include <pthread.h>
函数:int pthread_mutex_lock(pthread_mutex_t * __mutex);
功能:Wait until lock for MUTEX becomes available and lock it.


2.5 pthread_mutex_timedlock
头文件:#include <pthread.h>
函数:int pthread_mutex_timelock(pthread_mutex_t * __mutex,
const struct timespec * __abstime);
功能:Wait until lock becomes available, or specified time passes.


2.6 pthread_mutex_unlock
头文件:#include <pthread.h>
函数:int pthread_mutex_unlock(pthread_mutex_t * __mutex);
功能:Unlock MUTEX.


3.测试代码

#include <iostream>
using namespace std;

int gNum = 0;
pthread_mutex_t m;

void * threadProc(void * param)
{
        pthread_mutex_lock(&m);
        for (int i = 0; i < 10; ++i){
                sleep(1);
                cout << (int)param << "gNum = " << ++gNum << endl;
        }
        pthread_mutex_unlock(&m);
}

int main()
{
        pthread_t tid1;
        pthread_t tid2;
        pthread_mutex_init(&m, NULL);

        pthread_create(&tid1, NULL, threadProc, (void *)1);
        pthread_create(&tid2, NULL, threadProc, (void *)2);

        pthread_mutex_destroy(&m);
        pthread_join(tid1, NULL);
        pthread_join(tid2, NULL);

        return 0;
}



版权声明:本文为ahyswang原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。