js引擎v8源码解析之平台相关(上篇)(基于v8 0.1.5)_js v8引擎 for源码-程序员宅基地

技术标签: v8引擎源码分析  

1 VirtualMemory

VirtualMemory是通过mmap申请一块内存,然后进行管理。

class VirtualMemory {
    
 public:
  // Reserves virtual memory with size. address_hint代表用户想映射的地址
  VirtualMemory(size_t size, void* address_hint = 0);
  ~VirtualMemory();

  // Returns whether the memory has been reserved.
  bool IsReserved();

  // Returns the start address of the reserved memory.
  void* address() {
    
    ASSERT(IsReserved());
    return address_;
  };

  // Returns the size of the reserved memory.
  size_t size() {
     return size_; }

  // Commits real memory. Returns whether the operation succeeded.
  bool Commit(void* address, size_t size);

  // Uncommit real memory.  Returns whether the operation succeeded.
  bool Uncommit(void* address, size_t size);

 private:
  // 管理的内存首地址,由mmap返回,用户可以自定义
  void* address_;  // Start address of the virtual memory.
  // 管理的内存大小
  size_t size_;  // Size of the virtual memory.
};

// Constants used for mmap.
static const int kMmapFd = -1;
static const int kMmapFdOffset = 0;


VirtualMemory::VirtualMemory(size_t size, void* address_hint) {
    
  // 映射一块内存,不能访问,私有的,不映射到文件,写的时候如果没有物理内存则报错
  address_ = mmap(address_hint, size, PROT_NONE,
                  MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
                  kMmapFd, kMmapFdOffset);
  size_ = size;
}


VirtualMemory::~VirtualMemory() {
    
  // 已经分配了虚拟内存则释放
  if (IsReserved()) {
    
    if (0 == munmap(address(), size())) address_ = MAP_FAILED;
  }
}

// 是否分配了虚拟内存
bool VirtualMemory::IsReserved() {
    
  return address_ != MAP_FAILED;
}

// 
bool VirtualMemory::Commit(void* address, size_t size) {
    
  // 修改一块虚拟内存的属性,MAP_FIXED说明分配的地址一定是address,而不能由操作系统自己选择,这里是修改属性,所以地址要固定。因为这块内存已经申请过了
  if (MAP_FAILED == mmap(address, size, PROT_READ | PROT_WRITE | PROT_EXEC,
                         MAP_PRIVATE | MAP_ANONYMOUS | MAP_FIXED,
                         kMmapFd, kMmapFdOffset)) {
    
    return false;
  }

  UpdateAllocatedSpaceLimits(address, size);
  return true;
}

// 修改某块虚拟内存的属性,变成不可访问
bool VirtualMemory::Uncommit(void* address, size_t size) {
    
  return mmap(address, size, PROT_NONE,
              MAP_PRIVATE | MAP_ANONYMOUS | MAP_NORESERVE,
              kMmapFd, kMmapFdOffset) != MAP_FAILED;
}

2 线程辅助类

PlatformData 是管理线程中,不同系统中的数据。这里只看linux系统。只保存了线程id。

class ThreadHandle::PlatformData : public Malloced {
    
 public:
  explicit PlatformData(ThreadHandle::Kind kind) {
    
    Initialize(kind);
  }

  void Initialize(ThreadHandle::Kind kind) {
    
    switch (kind) {
    
      case ThreadHandle::SELF: thread_ = pthread_self(); break;
      case ThreadHandle::INVALID: thread_ = kNoThread; break;
    }
  }
  pthread_t thread_;  // Thread handle for pthread.
};

ThreadHandle是对PlatformData的封装。


ThreadHandle::ThreadHandle(Kind kind) {
    
  data_ = new PlatformData(kind);
}


void ThreadHandle::Initialize(ThreadHandle::Kind kind) {
    
  data_->Initialize(kind);
}


ThreadHandle::~ThreadHandle() {
    
  delete data_;
}


bool ThreadHandle::IsSelf() const {
    
  // 当前执行的线程是不是管理的线程
  return pthread_equal(data_->thread_, pthread_self());
}


bool ThreadHandle::IsValid() const {
    
  return data_->thread_ != kNoThread;
}

3 Thread

// Thread
//
// Thread objects are used for creating and running threads. When the start()
// method is called the new thread starts running the run() method in the new
// thread. The Thread object should not be deallocated before the thread has
// terminated.

class Thread: public ThreadHandle {
    
 public:
  // Opaque data type for thread-local storage keys.
  enum LocalStorageKey {
    };

  // Create new thread.
  Thread();
  virtual ~Thread();

  // Start new thread by calling the Run() method in the new thread.
  void Start();

  // Wait until thread terminates.
  void Join();

  // Abstract method for run handler.
  virtual void Run() = 0;

  // Thread-local storage.
  static LocalStorageKey CreateThreadLocalKey();
  static void DeleteThreadLocalKey(LocalStorageKey key);
  static void* GetThreadLocal(LocalStorageKey key);
  static void SetThreadLocal(LocalStorageKey key, void* value);

  // A hint to the scheduler to let another thread run.
  static void YieldCPU();

 private:
  class PlatformData;
  PlatformData* data_;
  DISALLOW_EVIL_CONSTRUCTORS(Thread);
};


Thread::Thread() : ThreadHandle(ThreadHandle::INVALID) {
    
}


Thread::~Thread() {
    
}

// arg是this指针,见Start函数
static void* ThreadEntry(void* arg) {
    
  Thread* thread = reinterpret_cast<Thread*>(arg);
  // This is also initialized by the first argument to pthread_create() but we
  // don't know which thread will run first (the original thread or the new
  // one) so we initialize it here too.
  /*
    这里也设置一下线程id,因为如果新建完线程后,是新建的线程先执行,
    这时候pthread_create还没有给thread_赋值,然后在执行Run的时候如果使用thread_就有问题,还是空的
  */
  thread->thread_handle_data()->thread_ = pthread_self();
  ASSERT(thread->IsValid());
  // 子类需要实现的函数
  thread->Run();
  return NULL;
}


void Thread::Start() {
    
  // 创建一个线程,执行ThreadEntry函数,把线程id保存在thread_
  pthread_create(&thread_handle_data()->thread_, NULL, ThreadEntry, this);
  ASSERT(IsValid());
}

// 挂起,等待线程thread_结束
void Thread::Join() {
    
  pthread_join(thread_handle_data()->thread_, NULL);
}

// 创建一个用于线程保存数据kv结构体。保存返回的key,通过key可以访问value
Thread::LocalStorageKey Thread::CreateThreadLocalKey() {
    
  pthread_key_t key;
  int result = pthread_key_create(&key, NULL);
  USE(result);
  ASSERT(result == 0);
  return static_cast<LocalStorageKey>(key);
}

// 删除线程的数据
void Thread::DeleteThreadLocalKey(LocalStorageKey key) {
    
  pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
  int result = pthread_key_delete(pthread_key);
  USE(result);
  ASSERT(result == 0);
}

// 通过key获取数据
void* Thread::GetThreadLocal(LocalStorageKey key) {
    
  pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
  return pthread_getspecific(pthread_key);
}

// 通过key写入数据
void Thread::SetThreadLocal(LocalStorageKey key, void* value) {
    
  pthread_key_t pthread_key = static_cast<pthread_key_t>(key);
  pthread_setspecific(pthread_key, value);
}

// 让优先级比自己高或者等于自己的线程执行,如果没有,则自己继续执行 
void Thread::YieldCPU() {
    
  sched_yield();
}

4 互斥变量Mutex

Mutex是基类,具体实现在子类。


class Mutex {
    
 public:
  virtual ~Mutex() {
    }

  // Locks the given mutex. If the mutex is currently unlocked, it becomes
  // locked and owned by the calling thread, and immediately. If the mutex
  // is already locked by another thread, suspends the calling thread until
  // the mutex is unlocked.
  virtual int Lock() = 0;

  // Unlocks the given mutex. The mutex is assumed to be locked and owned by
  // the calling thread on entrance.
  virtual int Unlock() = 0;
};

LinuxMutex 是对linux下线程的封装。

class LinuxMutex : public Mutex {
    
 public:

  LinuxMutex() {
    
    pthread_mutexattr_t attrs;
    // 初始化属性结构体,用于设置互斥的一些属性,或者说策略
    int result = pthread_mutexattr_init(&attrs);
    ASSERT(result == 0);
    // 设置加锁类型,支持一个线程多次(递归)获得一个锁
    result = pthread_mutexattr_settype(&attrs, PTHREAD_MUTEX_RECURSIVE);
    ASSERT(result == 0);
    // 初始化互斥变量
    result = pthread_mutex_init(&mutex_, &attrs);
    ASSERT(result == 0);
  }

  virtual ~LinuxMutex() {
     pthread_mutex_destroy(&mutex_); }
  // 对linx线程的封装
  virtual int Lock() {
    
    int result = pthread_mutex_lock(&mutex_);
    return result;
  }

  virtual int Unlock() {
    
    int result = pthread_mutex_unlock(&mutex_);
    return result;
  }

 private:
  pthread_mutex_t mutex_;   // Pthread mutex for POSIX platforms.
};

5 Semaphore

// Semaphore
//
// A semaphore object is a synchronization object that maintains a count. The
// count is decremented each time a thread completes a wait for the semaphore
// object and incremented each time a thread signals the semaphore. When the
// count reaches zero,  threads waiting for the semaphore blocks until the
// count becomes non-zero.

class Semaphore {
    
 public:
  virtual ~Semaphore() {
    }

  // Suspends the calling thread until the counter is non zero
  // and then decrements the semaphore counter.
  virtual void Wait() = 0;

  // Increments the semaphore counter.
  virtual void Signal() = 0;
};

class LinuxSemaphore : public Semaphore {
    
 public:
  // 初始化信号量,资源数是count个
  explicit LinuxSemaphore(int count) {
      sem_init(&sem_, 0, count); }
  virtual ~LinuxSemaphore() {
     sem_destroy(&sem_); }
  // 没有可用资源,需要等待
  virtual void Wait() {
     sem_wait(&sem_); }
  // 多一个可用资源,如果有线程等待,则会被唤醒
  virtual void Signal() {
     sem_post(&sem_); }

 private:
  // linux信号量结构体
  sem_t sem_;
};
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/THEANARKH/article/details/103116092

智能推荐

KEIL文件移动脚本--网关脚本_nrfutil' 不是内部或外部命令,也不是可运行的程序-程序员宅基地

文章浏览阅读650次。上面是效果原因 每次都是编译在大文件里面我希望只有BIN文件在一个干净的地方写一个.BAT在任何地方都是可以执行的 最后挂在KEIL里面内容 mv.batFOR /F %%I IN ('DIR /B /S "D:\TSBrowserDownloads\DA145xx_SDK_for_handover\DA145xx_SDK\old\projects\Izar\src\Node_Dialog_DA14531_SHENNONG\Keil_5\out_DA14531\Ob..._nrfutil' 不是内部或外部命令,也不是可运行的程序

全面解析并解决计算机缺失msvcp80.dll文件的问题-程序员宅基地

文章浏览阅读427次,点赞24次,收藏17次。在使用计算机过程中,有时会遇到“计算机缺失msvcp80.dll文件”的错误提示,这直接影响了部分应用程序的正常运行。msvcp80.dll是Microsoft Visual C++ 2005 redistributable runtime library(即VC++ 2005运行时库)的一部分,对于基于VC++ 2005编译的应用程序至关重要。本文将深入探究此问题产生的原因,并提出切实可行的解决方案。_msvcp80.dll

<读书笔记>《JS DOM编程艺术》-程序员宅基地

文章浏览阅读54次。2016/03/04 12:00第一二章:JS的简史以及基本语法1.P112.variable3.P13 等于4.P135.P14 转义字符6.关联数组不是一个好习惯7.P18 对象8.P31firefox和chrome的兼容性;+1900,IE好着呢;第三章:强大的DOM编程1.DOM:Document O..._dom编程艺术第3版下载

高级信息系统项目管理师—论文—进度管理_信息系统集成项目管理工程师高级论文-程序员宅基地

文章浏览阅读9.6k次,点赞7次,收藏35次。摘要:2015年3月,我作为项目经理参与了某公司与XX市交通运输局的道路交通智能监控抓拍系统的建设工作。我作为项目经理,主要进行了需求分析、系统设计、项目管理等工作。我十分重视项目的进度管理,运行丰富的项目管理经验,结合进度管理理论,对项目的各阶段进行了进度管理:规划进度管理、定义活动、估算活动顺序、估算活动资源、估算活动持续时间、制定进度计划、控制项目进度等过程全面展开对沟通的管控。依照项目管理..._信息系统集成项目管理工程师高级论文

java Lambda-程序员宅基地

文章浏览阅读317次。 https://www.cnblogs.com/heimianshusheng/p/5663913.html

UI设计师未来职业规划_ui设计未来工作期望-程序员宅基地

文章浏览阅读1.7k次。  近几年UI设计行业一直都比较火,不少其他行业的设计师都转行UI设计。这时候可能就会有小伙伴问未来职业规范怎么做才能脱颖而出呢?今天胡老师和大家来探讨一下。  现在的UI设计的市场需求和刚兴起那会截然不同,那时只要会设计图标简单的界面就可以找到一份很不错工作。而且薪资也比较可观。因此UI设计瞬间爆火,还有很多设计同行也分分转战UI设计。这个职位的特点,一定是指数型的,好的人会越来越好,一般的人面对的门槛则会提高。其实任何行业和职业都是这样的,只不过在互联网的设计师、工程师(以及其他职位)中,尤其明显。_ui设计未来工作期望

随便推点

使用nfs之后初始化mysql失败_influxdb数据库 nfs存储初始化失败-程序员宅基地

文章浏览阅读1.7k次。将nfs作为mysql的数据目录输出后,在另一台主机上启动mysql进程时,会出现如下这样的错误,究其原因,其实还是nfs自身设计的缺陷。 初始化就是使用特定的用户,去特定的目录去更新mysql,虽然说添加mysql用户之后,所有的对数据的修改权限都是以mysql用户执行的,而且nfs的数据目录也都设计成了mysql,常理是没有问题的。但是,执行mysql_ins_influxdb数据库 nfs存储初始化失败

ORC事务表与Hyperbase表的区别_星环 hyperbase、orc、text表区别-程序员宅基地

文章浏览阅读2.5k次。今天有客户问了我一下关于ORC事务表与Hyperbase表的区别问题,我回答的不是特别好,所以这里总结一下他们两个的区别,以便能掌握得更加深入些。ORC事务表:轻量级索引,支持CRUD操作,但是不建议大规模的单条增删改查,因为TDH(TDH是星环自研的一套大数据平台,类似于CDH,但是进行了很多的优化)是大数据数仓系统,是需要使用批量进行增删改查,索引单条操作的性能会降低;事务表需要进..._星环 hyperbase、orc、text表区别

Mybatis_"mybatis the content of element type \"choose\" mu-程序员宅基地

文章浏览阅读261次。Mybatis环境:JDK1.8Mysql5.7maven 3.6.1IDEA回顾JDBCMysqlJava基础MavenJunit1. 简介1.1 什么是MybatisMyBatis 是一款优秀的持久层框架它支持自定义 SQL、存储过程以及高级映射MyBatis 免除了几乎所有的 JDBC 代码以及设置参数和获取结果集MyBatis 可以通过简单的 XML 或注解来配置和映射原始类型、接口和 Java POJO(Plain Old Java _"mybatis the content of element type \"choose\" must match \"(when*,otherwise?)"

【预测模型】基于萤火虫算法优化bp神经网络实现数据预测matlab源码_mape1=mean(abs(error./output_test));-程序员宅基地

文章浏览阅读700次。1 算法介绍1.1 萤火虫算法算法基本思想描述如下:在群体中,每个萤火虫个体被随机分布在目标函数定义的空间中,初始阶段,所有的萤火虫都具有相同的荧光素值和动态决策半径。其中,每个萤火虫个体根据来自动态决策半径内所有邻居萤火虫信号的强弱来决定其移动的方向。萤火虫的动态决策半径会随着在它范围内萤火虫个体的数目而变化,每个萤火虫的荧光素也会随着决策半径内萤火虫个体的数目而改变。萤火虫群优化算法是无记忆的,无需目标函数的全局信息和梯度信息,具有计算速度快,调节参数少,易于实现等特点。萤火虫进化过程中,每次._mape1=mean(abs(error./output_test));

mybatis自动生成代码时报错:The server time zone value ‘�й���׼ʱ��‘ is unrecognized or represents more than one_mybatisplus报错the server time zone value ' й-程序员宅基地

文章浏览阅读588次。这种情况一般是因为在generatorConfig.xml文件中,连接数据库时缺少serverTimeZone导致的,在数据库连接上加上serverTimeZone=UTC即可解决。generatorConfig.xml代码如下:<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE generatorConfiguration PUBLIC "-//mybatis.org//DTD MyBatis Generator.._mybatisplus报错the server time zone value ' й

相机标定-机器视觉基础(理论推导、Halcon和OpenCV相机标定)_机器视觉标定-程序员宅基地

文章浏览阅读5.3k次,点赞13次,收藏109次。相机标定是获得目标工件精准坐标信息的基础。首先,必须进行相机内参标定,构建一个模型消除图像畸变;其次,需要对相机和机器人的映射关系进行手眼标定,构建一个模型将图像坐标系上的点映射到世界坐标系。主要分为背景知识、相机内外参模型推导、编程代码实现三个部分。_机器视觉标定

推荐文章

热门文章

相关标签