静态初始化互斥锁,方法如下: pthread_mutex_t mutex=PTHREAD_MUTEX_INITIALIZER;
动态方式是采用pthread_mutex_init()函数来初始化互斥锁,API定义如下: int pthread_mutex_init(pthread_mutex_t *mutex, const pthread_mutexattr_t *mutexattr)
pthread_mutex_lock( pthread_mutex_t *mutex) :
pthread_mutex_unlock( pthread_mutex_t *mutex);
pthread_mutex_trylock( pthread_mutex_t *mutex); 非阻塞调用模式
int pthread_join(pthread_t thread, void **retval); 线程阻塞函数
void pthread_exit(void *retval); 结束现场返回 ,通过retval
条件锁:
pthread_cond_t condmutex = PTHREAD_COND_INITIALIZER;
pthread_cond_wait( &condmutex, &mutex); 此函数是阻塞函数,调用前后锁都是锁住的,阻塞过程中函数会打开锁,
pthread_cond_signal(&cond); 发送信号前锁必须是开的,否则无法跳出阻塞。
/* * 1p.c * * Created on: Jan 18, 2017 * Author: s */ #include <stdio.h> #include <stdlib.h> #include <stdbool.h> #include <pthread.h> unsigned count = 0; pthread_mutex_t count_lock = PTHREAD_MUTEX_INITIALIZER; pthread_cond_t cond = PTHREAD_COND_INITIALIZER; void decrement_count() { pthread_mutex_lock (&count_lock); sleep(1); //while(count==0) pthread_cond_wait( &cond, &count_lock); count=count -1; pthread_mutex_unlock (&count_lock); printf("decrement done,count = %d ",count); } void increment_count(){ pthread_mutex_lock(&count_lock); if(count==0) // pthread_cond_signal(&cond); count=count+1; pthread_mutex_unlock(&count_lock); printf("increment done.count = %d ",count); } void test() { sleep(5); pthread_mutex_lock(&count_lock); printf("sleep 5s "); pthread_cond_signal(&cond); pthread_mutex_unlock(&count_lock); } int main() { pthread_t idone,idtwo,id3; int ret; ret=pthread_create(&idone,NULL,(void *) decrement_count,NULL); if(ret!=0){ printf ("Create pthread 1 error!/n"); exit (1); } ret=pthread_create(&idtwo,NULL,(void *) increment_count,NULL); if(ret!=0){ printf ("Create pthread 2 error!/n"); exit (1); } ret=pthread_create(&id3,NULL,(void *) test,NULL); if(ret!=0){ printf ("Create pthread 3 error!/n"); exit (1); } printf("count = %d ",count); printf(" exec: pthread_join(idone,NULL); "); pthread_join(idone,NULL); pthread_join(idtwo,NULL); pthread_join(id3,NULL); printf("done "); return 0; }
对共享资源操作前一定要获得锁.
完成操作以后一定要释放锁.
尽量短时间地占用锁.
如果有多锁, 如获得顺序是ABC连环扣, 释放顺序也应该是ABC.
线程错误返回时应该释放它所获得的锁