专栏首页原创分享线程源码分析之mutex.c(基于linuxthreads2.0.1)

线程源码分析之mutex.c(基于linuxthreads2.0.1)

mutex即互斥,用于控制多线程间同步、互斥访问资源。

相关的结构体。

/* Mutexes (not abstract because of PTHREAD_MUTEX_INITIALIZER).  */
typedef struct
{
  // 自旋锁
  int m_spinlock;		/* Spin lock to guarantee mutual exclusion.  */
  // 用于递归加锁,即某个线程多次获取了该互斥变量。m_count记录了次数
  int m_count;			/* 0 if free, > 0 if taken.  */
  // 记录谁获取了该互斥变量,在递归加锁的时候会使用这个字段
  pthread_t m_owner;		/* Owner of mutex (for recursive mutexes) */
  // 互斥变量的类型,递归或非递归
  int m_kind;			/* Kind of mutex */
  // 等待该互斥变量的线程队列
  struct _pthread_queue m_waiting; /* Threads waiting on this mutex.  */
} pthread_mutex_t;
// 初始化互斥变量,类型是递归或非递归
#define PTHREAD_MUTEX_INITIALIZER \
  {0, 0, 0, PTHREAD_MUTEX_FAST_NP, {0, 0}}
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \
  {0, 0, 0, PTHREAD_MUTEX_RECURSIVE_NP, {0, 0}}

下面是实现的代码。

/* Linuxthreads - a simple clone()-based implementation of Posix        */
/* threads for Linux.                                                   */
/* Copyright (C) 1996 Xavier Leroy (Xavier.Leroy@inria.fr)              */
/*                                                                      */
/* This program is free software; you can redistribute it and/or        */
/* modify it under the terms of the GNU Library General Public License  */
/* as published by the Free Software Foundation; either version 2       */
/* of the License, or (at your option) any later version.               */
/*                                                                      */
/* This program is distributed in the hope that it will be useful,      */
/* but WITHOUT ANY WARRANTY; without even the implied warranty of       */
/* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the        */
/* GNU Library General Public License for more details.                 */

/* Mutexes */

#include <errno.h>
#include <sched.h>
#include <stddef.h>
#include "pthread.h"
#include "internals.h"
#include "spinlock.h"
#include "queue.h"
#include "restart.h"

// 利用属性结构体初始化mutex节点
int __pthread_mutex_init(pthread_mutex_t * mutex,
                       const pthread_mutexattr_t * mutex_attr)
{
  mutex->m_spinlock = 0;
  mutex->m_count = 0;
  mutex->m_owner = NULL;
  mutex->m_kind =
    mutex_attr == NULL ? PTHREAD_MUTEX_FAST_NP : mutex_attr->mutexkind;
  queue_init(&mutex->m_waiting);
  return 0;
}
weak_alias (__pthread_mutex_init, pthread_mutex_init)

// 销毁互斥锁
int __pthread_mutex_destroy(pthread_mutex_t * mutex)
{
  int count;
  acquire(&mutex->m_spinlock);
  count = mutex->m_count;
  release(&mutex->m_spinlock);
  // 正在被使用
  if (count > 0) return EBUSY;
  return 0;
}
weak_alias (__pthread_mutex_destroy, pthread_mutex_destroy)

// 非阻塞式获取锁
int __pthread_mutex_trylock(pthread_mutex_t * mutex)
{
  pthread_t self;

  acquire(&mutex->m_spinlock);
  switch(mutex->m_kind) {
  case PTHREAD_MUTEX_FAST_NP:
    // 还没有被使用,则使用数加一,返回成功
    if (mutex->m_count == 0) {
      mutex->m_count = 1;
      release(&mutex->m_spinlock);
      return 0;
    }
    break;
  // 递归获取互斥变量
  case PTHREAD_MUTEX_RECURSIVE_NP:
    self = thread_self();
    // 等于0则说明还没有被获取过,可以直接获取,或者已经被当前线程获取了,则次数加一
    if (mutex->m_count == 0 || mutex->m_owner == self) {
      mutex->m_count++;
      mutex->m_owner = self;
      release(&mutex->m_spinlock);
      return 0;
    }
    break;
  default:
    return EINVAL;
  }
  release(&mutex->m_spinlock);
  return EBUSY;
}
weak_alias (__pthread_mutex_trylock, pthread_mutex_trylock)

// 阻塞式获取互斥变量
int __pthread_mutex_lock(pthread_mutex_t * mutex)
{
  pthread_t self;

  while(1) {
    acquire(&mutex->m_spinlock);
    switch(mutex->m_kind) {
    case PTHREAD_MUTEX_FAST_NP:
      if (mutex->m_count == 0) {
        mutex->m_count = 1;
        release(&mutex->m_spinlock);
        return 0;
      }
      self = thread_self();
      break;
    case PTHREAD_MUTEX_RECURSIVE_NP:
      self = thread_self();
      // 等于0或者本线程已经获得过该互斥锁,则可以重复获得,m_count累加
      if (mutex->m_count == 0 || mutex->m_owner == self) {
        mutex->m_count++;
        // 标记该互斥锁已经被本线程获取
        mutex->m_owner = self;
        release(&mutex->m_spinlock);
        return 0;
      }
      break;
    default:
      return EINVAL;
    }
    /* Suspend ourselves, then try again */
    // 获取失败,需要阻塞,把当前线程插入该互斥锁的等待队列
    enqueue(&mutex->m_waiting, self);
    release(&mutex->m_spinlock);
    // 挂起等待唤醒
    suspend(self); /* This is not a cancellation point */
  }
}
weak_alias (__pthread_mutex_lock, pthread_mutex_lock)

int __pthread_mutex_unlock(pthread_mutex_t * mutex)
{
  pthread_t th;

  acquire(&mutex->m_spinlock);
  switch (mutex->m_kind) {
  case PTHREAD_MUTEX_FAST_NP:
    mutex->m_count = 0;
    break;
  case PTHREAD_MUTEX_RECURSIVE_NP:
    mutex->m_count--;
    if (mutex->m_count > 0) {
      release(&mutex->m_spinlock);
      return 0;
    }
    mutex->m_count = 0; /* so that excess unlocks do not break everything */
    break;
  default:
    return EINVAL;
  }
  // 取出一个被阻塞的线程(如果有的话),唤醒他
  th = dequeue(&mutex->m_waiting);
  release(&mutex->m_spinlock);
  if (th != NULL) restart(th);
  return 0;
}
weak_alias (__pthread_mutex_unlock, pthread_mutex_unlock)

int __pthread_mutexattr_init(pthread_mutexattr_t *attr)
{
  attr->mutexkind = PTHREAD_MUTEX_FAST_NP;
  return 0;
}
weak_alias (__pthread_mutexattr_init, pthread_mutexattr_init)

int __pthread_mutexattr_destroy(pthread_mutexattr_t *attr)
{
  return 0;
}
weak_alias (__pthread_mutexattr_destroy, pthread_mutexattr_destroy)

int __pthread_mutexattr_setkind_np(pthread_mutexattr_t *attr, int kind)
{
  if (kind != PTHREAD_MUTEX_FAST_NP && kind != PTHREAD_MUTEX_RECURSIVE_NP)
    return EINVAL;
  attr->mutexkind = kind;
  return 0;
}
weak_alias (__pthread_mutexattr_setkind_np, pthread_mutexattr_setkind_np)

int __pthread_mutexattr_getkind_np(const pthread_mutexattr_t *attr, int *kind)
{
  *kind = attr->mutexkind;
  return 0;
}
weak_alias (__pthread_mutexattr_getkind_np, pthread_mutexattr_getkind_np)
// 保存init_routine只执行一次
int pthread_once(pthread_once_t * once_control, void (*init_routine)(void))
{
  if (testandset(once_control) == 0) init_routine();
  return 0;
}

本文分享自微信公众号 - 编程杂技(theanarkh),作者:theanarkh

原文出处及转载信息见文内详细说明,如有侵权,请联系 yunjia_community@tencent.com 删除。

原始发表时间:2019-10-07

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

我来说两句

0 条评论
登录 后参与评论

相关文章

  • js中的变量声明问题

    从1,,2中我们可以看出js引擎是先对var声明的变量进行注册,再对函数类型的变量进行注册。 而3和4是一样的原理,js引擎执行到这段代码时,首先注册var a...

    theanarkh
  • redux源码解析

    theanarkh
  • 线程源码分析之信号量(基于linuxthreads2.0.1)

    theanarkh
  • 多线程安全-iOS开发注意咯!!!

    但是并不是非常完美,因为多线程常常伴有资源抢夺的问题,作为一个高级开发人员并发编程那是必须要的,同时解决线程安全也成了我们必须要要掌握的基础

    iOSSir
  • 多线程安全-iOS开发注意咯!!!

    但是并不是非常完美,因为多线程常常伴有资源抢夺的问题,作为一个高级开发人员并发编程那是必须要的,同时解决线程安全也成了我们必须要要掌握的基础

    iOSSir
  • linux网络编程之posix 线程(三):posix 匿名信号量与互斥锁 示例生产者--消费者问题

    一、posix 信号量 信号量的概念参见这里。前面也讲过system v 信号量,现在来说说posix 信号量。 system v 信号量只能用于进程间同步,...

    s1mba
  • 一步一步实现读写锁

    多线程编程中,需要对共享变量进行加锁。但是频繁地加锁,会对程序效率有很大影响。在某些读多写少的场景下,多个线程进行读数据时,如果都加互斥锁,这显然是不必须的。于...

  • LiteOS内核教程05 | 互斥锁(共享资源保护)

    在多任务环境下,往往存在多个任务竞争同一共享资源的应用场景,互斥锁可被用于对共享资源的保护从而实现独占式访问。互斥锁(mutex)又称互斥型信号量,是一种特殊的...

    Mculover666
  • Linux 下c++多线程同步之信号量

    2.P操作(信号量值减一) 3.V操作(信号量值加一) 2和3步骤函数为: int semop(int semid ,struct sem...

    多凡
  • 【专知荟萃08】图像描述生成Image Caption知识资料全集(入门/进阶/论文/综述/视频/专家等)

    【导读】主题荟萃知识是专知的核心功能之一,为用户提供AI领域系统性的知识学习服务。主题荟萃为用户提供全网关于该主题的精华(Awesome)知识资料收录整理,使得...

    WZEARW

扫码关注云+社区

领取腾讯云代金券