mutex互斥锁线程控制
互斥锁是用一种简单的加锁方法来控制对共享资源的原子操作。
互斥锁只有两种状态,也就是上锁和解锁,可以把互斥锁看作某种意义上的全局变量。
在同一时刻只能有一个线程掌握某个互斥锁,拥有上锁状态的线程能够对共享资源进行操作。若其他线程希望上锁一个已经被上锁的互斥锁,则该线程就会挂起,直到上锁的线程释放掉互斥锁为止。
互斥锁的基本操作:
互斥锁初始化:pthread_mutex_init()
互斥锁上锁:pthread_mutex_lock()
互斥锁判断上锁:pthread_mutex_trylock()
互斥锁接锁:pthread_mutex_unlock()
消除互斥锁:pthread_mutex_destroy()
函数pthread_mutex_init
功能:初始化互斥锁
原型:int pthread_mutex_init(pthread_mutex_t * restrict mutex,const pthread_mutexattr_t * mutexattr);
参数:mutex:互斥锁
mutexattr:PTHREAD_MUTEX_INITIALIZER
快速互斥锁
返回值:成功0,错误 -1
函数pthread_mutex_lock
功能:对互斥锁上锁
原型:int pthread_mutex_lock(pthread_mutex_t * mutex);
int pthread_mutex_trylock(pthread_mutex_t * mutex);//判断是否上锁
int pthread_mutex_unlock(pthread_mutex_t * mutex);//解锁
int pthread_mutex_destroy(pthread_mutex_t * mutex);//销毁互斥锁
返回值:成功:0 出错:-1
//#include < stdio.h >
//#include < stdlib.h >
//#include < pthread.h >
//#define THREAD_NUM 3
//#define REPEAT_NUM 3
//#define DELAY_TIME_LEVELS 6.0
pthread_mutex_t mutex;
void *thrd_func(void *arg)
{
int thrd_num = (int)arg;
int delay_time =0, count=0;
int res;
res = pthread_mutex_lock(&mutex);
printf("Thread %d is starting\n", thrd_num);
for(count=0; count<REPEAT_NUM; count++)
{
printf("\tThread %d:job %d delay=%d\n", thrd_num,count);
}
printf("Thread %d finish\n", thrd_num);
pthread_mutex_unlock(&mutex);
pthread_exit(NULL);
}
int main(void)
{
pthread_t thread[THREAD_NUM];
int no=0, res;
void *thrd_ret;
pthread_mutex_init(&mutex, NULL);
for(no = 0 ; no < THREAD_NUM; no++)
{
res=pthread_create(&thread[no], NULL, thrd_func, (void *)no);
}
printf(“creatr threads success\nwaiting for threads to finish….\n”);
for(no = 0; no < THREAD_NUM; no++)
{
res=pthread_join(thread[no], &thrd_ret);
}
pthread_mutex_destroy(&mutex);
return 0;
}