【Linux线程同步专题】一、什么是线程同步、互斥量与死锁

简介: 【Linux线程同步专题】一、什么是线程同步、互斥量与死锁

什么是同步

同步就是指同时起步,协调一致。不同的对象,对同步的理解方式也不尽相同。比如说,设备同步是指在两个设备之间规定一个共同的时间参考;数据库同步是指让两个或多个数据库内容保持一致,或者按照需要部分保持一致;文件同步是指让两个或多个文件夹中的文件保持一致。而在多线程中,同步是指协同、协助、互相配合,主要目的是协调步骤,按照预先定好的顺序依次运行。线程同步就是指,一个线程在发出某一功能调用时,在没有得到结果之前,该调用不返回,并且同时其它线程为保证数据一致性,不能调用该功能。如果没有同步机制,会产生“与时间有关的错误 time related”,为了避免这种数据混乱,线程之间必须要同步。通过同步就可以解决这种与时间有关的错误,避免数据混乱。实际上,线程之间、进程之间、信号之间都需要同步机制。也就是说,多个控制流共同操作一个共享资源的情况,都需要同步。数据混乱主要有三个原因:

  • 资源共享(共享资源可能会导致数据混乱,而独享资源则不会)。
  • 调度随机,调度随机就会导致在访问数据的时候出现竞争。
  • 线程间缺乏同步机制

这三点中,前两点都是无法更改的,因为资源共享是提高数据传递效率的最佳方法,而一旦资源共享,就势必会出现竞争,只要存在竞争,就可能会导致数据混乱。所以,解决方法只能从同步机制下手,在访问共享资源的时候使用互斥机制。

互斥量mutex

1. 锁的初始化和销毁

  • 头文件及函数原型
#include <pthread.h>
/*销毁一个锁*/
int pthread_mutex_destroy(pthread_mutex_t *mutex);
/*初始化一个锁*/
int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
/*也可以初始化一个锁*/
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
  • 函数描述
    The pthread_mutex_destroy() function shall destroy the mutex object referenced by mutex; the mutex object becomes, in effect, uninitialized. An implementation may cause pthread_mutex_destroy() to set the object referenced by mutex to an invalid value. A destroyed mutex object can be reinitialized using pthread_mutex_init(); the results of otherwise referencing the object after it has been destroyed are undefined.
  • 函数参数
  • mutex:互斥量(锁),restrict关键字表示,凡是被restrict关键字修饰的变量,该变量所代表的内存块只能由该变量去修改,比如说这里的mutex,mutex变量代表的内存中的数据只能通过mutex变量去修改,不能通过其它指针等方式去修改。
  • attr:互斥量的属性,可以直接设为NULL。
  • 函数返回值
    If successful, the pthread_mutex_destroy() and pthread_mutex_init() functions shall return zero; otherwise, an error number shall be returned to indicate the error.

2. 给共享资源加锁

  • 头文件及函数原型
#include <pthread.h>
/*给共享资源加锁,如果共享资源已经加锁,则阻塞等待*/
int pthread_mutex_lock(pthread_mutex_t *mutex);
/*尝试加锁,如果共享资源已经加锁不会阻塞,会返回错误码和错误信息*/
int pthread_mutex_trylock(pthread_mutex_t *mutex);
int pthread_mutex_unlock(pthread_mutex_t *mutex);
  • 函数描述
  • The mutex object referenced by mutex shall be locked by calling pthread_mutex_lock(). If the mutex is already locked, the calling thread shall block until the mutex becomes available. This operation shall return with the mutex object referenced by mutex in the locked state with the calling thread as its owner. 如果当前资源可以获得则加锁成功;如果当前资源已经被其它线程加锁,那么将阻塞等待。
  • The pthread_mutex_trylock() function shall be equivalent to pthread_mutex_lock(), except that if the mutex object referenced by mutex is currently locked (by any thread, including the current thread), the call shall return immediately. If the mutex type is PTHREAD_MUTEX_RECURSIVE and the mutex is currently owned by the calling thread, the mutex lock count shall be incremented by one and the pthread_mutex_trylock() function shall immediately return success.
  • The pthread_mutex_unlock() function shall release the mutex object referenced by mutex. The manner in which a mutex is released is dependent upon the mutex’s type attribute. If there are threads blocked on the mutex object referenced by mutex when pthread_mutex_unlock() is called, resulting in the mutex becoming available, the scheduling policy shall determine which thread shall acquire the mutex.
  • 函数参数
    mutex:pthread_mutex_init初始化得到的锁。
  • 函数返回值
    If successful, the pthread_mutex_lock() and pthread_mutex_unlock() functions shall return zero; otherwise, an error number shall be returned to indicate the error. The pthread_mutex_trylock() function shall return zero if a lock on the mutex object referenced by mutex is acquired. Otherwise, an error number is returned to indicate the error.
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>
#include <stdio.h>
/*初始化一个锁*/
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
void* th1(void* arg)
{
    while(1)
    {
        /*上锁*/
        pthread_mutex_lock(&mutex);
        /*进入临界区,都要打屏,会竞争*/
        printf("11111");
        sleep(rand()%3);
        printf("22222\n");
        /*释放锁*/
        pthread_mutex_unlock(&mutex); /*加锁一定要最小区域加锁,一旦离开共享资源区,立即释放锁*/
        sleep(rand()%3);
    }
}
void* th2(void* arg)
{
    while(1)
    {
        pthread_mutex_lock(&mutex); /*若加锁失败,阻塞等待*/
        printf("aaaaa");
        sleep(rand()%3);
        printf("bbbbb\n");
        pthread_mutex_unlock(&mutex);
        sleep(rand()%3);
    }
}
int main(int argc, char* argv[])
{
    pthread_t tid[2];
    pthread_create(&tid[0], NULL, th1, NULL);
    pthread_create(&tid[1], NULL, th2, NULL);
    pthread_join(tid[0], NULL);
    pthread_join(tid[1], NULL);
    return 0;
}

3. 死锁

死锁主要有两种情况

  • 加锁之后,再一次加锁,那么第二个锁将会永久阻塞。
  • 交叉锁,同一个临界资源有两把锁k1和k2,此时线程1和线程2分别持有k1和k2导致永久阻塞;可以通过给锁的申请限制申请顺序来解决,或者已拥有一把锁,当另一把锁不可获取的时候,释放已持有的锁。

实际上,互斥量mutex只是建议锁,也就是说即使不加锁也能访问共享资源,并非操作系统强制只有加锁才能访问。

相关文章
|
5天前
多线程(死锁)
多线程(死锁)
15 2
|
6天前
|
算法 Java
Java多线程基础-13:一文阐明死锁的成因及解决方案
死锁是指多个线程相互等待对方释放资源而造成的一种僵局,导致程序无法正常结束。发生死锁需满足四个条件:互斥、请求与保持、不可抢占和循环等待。避免死锁的方法包括设定加锁顺序、使用银行家算法、设置超时机制、检测与恢复死锁以及减少共享资源。面试中可能会问及死锁的概念、避免策略以及实际经验。
15 1
|
11天前
|
设计模式 安全 Java
【Linux 系统】多线程(生产者消费者模型、线程池、STL+智能指针与线程安全、读者写者问题)-- 详解
【Linux 系统】多线程(生产者消费者模型、线程池、STL+智能指针与线程安全、读者写者问题)-- 详解
|
11天前
|
安全 算法 Linux
【Linux 系统】多线程(线程控制、线程互斥与同步、互斥量与条件变量)-- 详解(下)
【Linux 系统】多线程(线程控制、线程互斥与同步、互斥量与条件变量)-- 详解(下)
|
11天前
|
存储 Linux 程序员
【Linux 系统】多线程(线程控制、线程互斥与同步、互斥量与条件变量)-- 详解(中)
【Linux 系统】多线程(线程控制、线程互斥与同步、互斥量与条件变量)-- 详解(中)
|
11天前
|
缓存 Linux 调度
【Linux 系统】多线程(线程控制、线程互斥与同步、互斥量与条件变量)-- 详解(上)
【Linux 系统】多线程(线程控制、线程互斥与同步、互斥量与条件变量)-- 详解(上)
|
18天前
|
Linux C语言 调度
|
18天前
|
Linux
linux线程创建等待及退出总结
linux线程创建等待及退出总结
|
18天前
|
Unix Linux 调度
linux线程与进程的区别及线程的优势
linux线程与进程的区别及线程的优势