转自:https://www.cnblogs.com/farbeyond/p/4482859.html
作者:farbeyond
线程中互斥锁使用的步骤与信号量相似!
1、首先定义互斥锁变量,并初始化
pthread_mutex_t mutex_lock;
pthread_mutex_init(&mutex_lock,NULL);
2、在操作前对互斥量进行加锁操作
pthread_mutex_lock(&mutex_lock);
3、操作完毕后进行解锁操作
pthread_mutex_unlock(&mutex_lock);
所有操作均在加锁和解锁操作之间进行,保证同时仅仅对有一个操作对关键变量或是区域进行操作。
下面是自己写的一个小程序,对主函数对变量自加操作,而线程函数进行自减操作。
(该程序有个小bug,看官可执行运行一下,就知道结果了,高手一看就知道问题在哪里,哈哈!卖个关子!)
pthread_mutex_lock(&mutex_lock);对某个互斥锁变量进行加锁操作时,当该变量已经被另外一个线程锁住时,该线程会被阻塞(英文原文为block),可以理解为休眠。
由操作系统基本原理可知,当进程处于就绪状态时,才会获得处理机的时间片,换句话说就是能能被调度到处理机上执行,而阻塞状态则不能。
因此一个线程被阻塞后,将不会执行,处于等待状态,通常是等待某个事件发生或到来。因此,一个对已经加锁的变量进行加锁的线程将被阻塞,其只能等待另外一个线程解锁,才能继续执行。
- #include <stdio.h>
- #include <unistd.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <string.h>
- #include <errno.h>
- void *thread_function(void *arg);
- pthread_mutex_t mutex_lock;
- int globaltmp=0;
- int main(){
- int res;
- pthread_t pthread_tmp;
- pthread_mutex_init(&mutex_lock,NULL);
- pthread_mutex_lock(&mutex_lock);
- res = pthread_create(&pthread_tmp,NULL,thread_function,NULL);
- if(res != 0){
- perror("thread creation failed!");
- exit(EXIT_FAILURE);
- }
- while(1){
- pthread_mutex_unlock(&mutex_lock);
- sleep(2);
- globaltmp++;
- printf("in the main func,globaltmp=%d\n",globaltmp);
- res = pthread_mutex_lock(&mutex_lock);
- // if(res == EDEADLK)
- {
- // printf("it has been locked in the thread!\n");
- }
- // printf(" main func res =%d\n",res);
- sleep(2);
- }
- res = pthread_join(pthread_tmp,NULL);
- if(res != 0 ){
- perror("thread join is failure");
- exit(EXIT_FAILURE);
- }
- printf("thread joined!\n");
- pthread_mutex_destroy(&mutex_lock);
- return 0;
- }
- void *thread_function(void *arg){
- int res ;
- res = pthread_mutex_lock(&mutex_lock);
- if(res == EDEADLK)
- printf("it has been locked in the main!\n");
- while(1)
- {
- pthread_mutex_unlock(&mutex_lock);
- sleep(1);
- globaltmp--;
- printf("in the pthread func,globaltmp=%d\n",globaltmp);
- // printf("I am in the pthread func\n");
- res = pthread_mutex_lock(&mutex_lock);
- // printf("thread func res=%d\n",res);
- // if(res == EDEADLK)
- // printf("it has been locked in the main!\n");
- sleep(1);
- }
- pthread_exit(NULL);
- }