2014年6月10日 星期二
Newlib reentrancy
引用Newlib 的原文
Reentrancy is a characteristic of library functions which allows multiple processes to use the same address space with assurance that the values stored in those spaces will remain constant between calls.
意思是說,當某process A 執行function到一半的時候, 允許其他processes B 去執行,並且可以確保B執行完畢之後,A 還可以正確的執行剩下的指令。
一開始我對這個reentrancy 的定義很confused,原因是我記得reentrancy 跟thread-safe 是兩件事,可參考 Wiki Reentrancy ,reentrancy 是在談single process 環境下,user code 與ISR的關係 (這並不是multithread)。
但Newlib 很顯然是把reentrancy 跟multithreading 扯在一起了。為了繼續看下去,只好先接受它的定義囉。
為什麼library function 要reentrant ?
最簡單的例子是errno
每個thread 都應該維護自己的errno,不可以影響其他thread 的執行。
所以Newlib 維護了一個reentrancy structure struct _reent,內含所有會被library 修改到的global variables。errno 當然是其中一個member,而且還是第一個。(因為它太常被修改到了)
而user 使用到的errno 其實並不是變數,而是macro
這個macro 會替換成_reent 內的errno。
再繼續看下去之前,先談談
其實Newlib 也提供不需要reentrancy 的版本。
而這些版本的code 只要共同存取一個global reentrancy structure 就好了
(根本就不需要reentrant 了,還要去集中管理,這設計很奇怪)
newlib/libc/include/sys/errno.h
#ifndef _REENT_ONLY
#define errno (*__errno())
extern int *__errno _PARAMS ((void));
#endif
newlib/libc/errno/errno.c
int *
__errno ()
{
return &_REENT->_errno;
}
newlib/libc/include/sys/reent.h
#if defined(__DYNAMIC_REENT__) && !defined(__SINGLE_THREAD__)
#ifndef __getreent
struct _reent * _EXFUN(__getreent, (void));
#endif
# define _REENT (__getreent())
#else /* __SINGLE_THREAD__ || !__DYNAMIC_REENT__ */
# define _REENT _impure_ptr#endif /* __SINGLE_THREAD__ || !__DYNAMIC_REENT__ */
newlib/libc/reent/impure.c
static struct _reent __ATTRIBUTE_IMPURE_DATA__ impure_data = _REENT_INIT (impure_data);
struct _reent *__ATTRIBUTE_IMPURE_PTR__ _impure_ptr = &impure_data;
所以得到 _REENT 是指到global reentrancy structure 的指標。
(不需要reentrancy 的code 都可以使用_REENT)
但NEWLIB 同時也提供了要reentrant 的版本
通常這些function 都是prependding ‘_’ 跟pendding ‘_r"’
例如: fopen
FILE *
_DEFUN(_fopen_r, (ptr, file, mode),
struct _reent *ptr _AND
_CONST char *__restrict file _AND
_CONST char *__restrict mode)
{
…
}
#ifndef _REENT_ONLY
FILE *
_DEFUN(fopen, (file, mode),
_CONST char *file _AND
_CONST char *mode)
{
return _fopen_r (_REENT, file, mode);
}
#endif
fopen 是non-reentrant 的版本 ,所以它使用global _REENT
_fopen_r 是reentrant 的版本,ptr是用來接收自己的unique _reent
所以如果_fopen_r 要設定errno,只要使用ptr->_errno 就可以改到自己的unique _reent 囉
訂閱:
張貼留言 (Atom)
沒有留言:
張貼留言