现在的位置: 首页 > 综合 > 正文

Thread safety of google/dense_hash_map

2013年03月15日 ⁄ 综合 ⁄ 共 1191字 ⁄ 字号 评论关闭

一个可重入的函数。简单理解为可以被中断的函数。就是说,你可以在这个函数执行的任何时候中断他的运行,在任务调度下去执行另外一段代码而不会出现什么错误。而不可重入的函数由于使用了一些系统资源,比如全局变量区,中断向量表等等,所以他如果被中断的话,可能出现问题,这类函数是不能运行在多任务环境下的。

  基本上下面的函数是不可重入的
  (1)函数体内使用了静态的数据结构;
  (2)函数体内调用了malloc()或者free()函数;
  (3)函数体内调用了标准I/O函数。
  把一个不可重入函数变成可重入的唯一方法是用可重入规则来重写他。
  其实很简单,只要遵守了几条很容易理解的规则,那么写出来的函数就是可重入的。
  第一,不要使用全局变量。因为别的代码很可能覆盖这些变量值。
  第二,在和硬件发生交互的时候,切记执行类似disinterrupt()之类的操作,就是关闭硬件中断。完成交互记得打开中断,在有些系列上,这叫做“进入/退出核心”或者用OS_ENTER_KERNAL/OS_EXIT_KERNAL来描述。//这是临界区保护

  第三,不能调用任何不可重入的函数。
  第四,谨慎使用堆栈。最好先在使用前先OS_ENTER_KERNAL。

  还有一些规则,都是很好理解的,总之,时刻记住一句话:保证中断是安全的!

A const C++ object of reentrant type (most are) is generally assumed to be thread-safe.

The documentation of dense_hash_map doesn't specify anything regarding thread-safety, so the most defensive approach would be to assume it isn't even reentrant. It takes unprotected global mutable state to make a class non-reentrant, though, and it's hard to
find an argument for dense_hash_map to require that, but seeing as it stores its contents to disk, that might be all you can hope for. To assume the thing is thread-safe even on mutable operations is far-fetched without confirmation from the documentation.

Barring documentation, you might want to have a look at the implementation to see whether you can verify reentrancy for at least some subset of the API.

抱歉!评论已关闭.