pthread_mutex_t pthread_mutex_lock() pthread_ulock() pthread_guard pthread_cond_t wait用法

时间:2021-10-14 20:57:14

pthread_mutex_t //锁的数据类型

pthread_mutex_lock()//加锁,如果当前其他线程正占用锁,那么阻塞,直到得到锁

pthread_ulock()//解锁

pthread_guard//封装成具有作用域特性的锁

pthread_cond_t wait //条件变量,一般用于多个线程的同步

pthread_destory()//销毁锁

案例一:

初始化:

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

 

每个要改变公共数据的线程中 :

  some code

  pthread_mutex_lock(mutex)

  do some reading or writing

  pthread_mutex_unlock(mutex)

  some code

案例2:

pthread_cond_t  cond = PTHREAD_COND_INITIALIZER

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;

bool flag

线程一:

  some code

  while(1)

    pthread_lock(mutex)

    some code

    pthread_signal(cond)

    some code

    pthread_unlock(mutex)

线程二:

  while(1)

    pthread_lock(mutex)

    some code

    pthread_cond_wait(cond)

    some code

    pthread_unlock(mutex)