假设我正在用C语言构建一个库,用于spork quuxes。
要成功spork quuxes,需要两个状态变量:
static int quux_state;
static char* quux_address;
/* function to spork quuxes found in a file,
reads a line from the file each time it's called. */
void spork_quux(FILE*);
如果我将数据存储为全局变量,那么只有一个客户端能够同时 spork quuxes,否则状态变量将被第二个调用者搞乱,可能会导致灾难。
问题是如何在C语言中设计可重入库?
我已经考虑了以下情况,但没有得出令人满意的结论。
在下面的情况中,问题是如何将每个状态与客户端关联起来?
/* library handles all state data allocation */
static int* quux_state;
static char** quux_address;
在以下情况下,客户端可以操纵状态,这是非常不希望的。
/* let each client store state */
typedef struct { int state; char* address; } QuuxState;
QuuxState spork_quux(FILE*);
所以,如何正确地做到这一点呢?