目的
对于数据库来说,文件读写操作异常频繁,需要借助cache提高IO读写的效率。在MySQL源码中,数据结构IO_CACHE及其相关处理函数,正是提供了对于文件IO的CACHE读写策略。其中IO_CACHE_SHARE数据结构,提供了共享CACHE的读写策略,用于多线程共享读取CACHE。
数据结构
IO_CACHE数据结构的定义在MySQL源码的/include/my_sys.h文件中,该数据结构的定义较复杂,具体定义如下所示:
点击(此处)折叠或打开
enum cache_type
{ TYPE_NOT_SET= 0, READ_CACHE, WRITE_CACHE,
SEQ_READ_APPEND /* sequential read or append */,
READ_FIFO, READ_NET,WRITE_NET};
typedef int (*IO_CACHE_CALLBACK)(struct st_io_cache*);
typedef struct st_io_cache_share
{
mysql_mutex_t mutex; /* To sync on reads into buffer. */
mysql_cond_t cond; /* To wait for signals. */
mysql_cond_t cond_writer; /* For a synchronized writer. */
/* Offset in file corresponding to the first byte of buffer. */
my_off_t pos_in_file;
/* If a synchronized write cache is the source of the data. */
struct st_io_cache *source_cache;
uchar *buffer; /* The read buffer. */
uchar *read_end; /* Behind last valid byte of buffer. */
int running_threads; /* threads not in lock. */
int total_threads; /* threads sharing the cache. */
int error; /* Last error. */
#ifdef NOT_YET_IMPLEMENTED
/* whether the structure should be free'd */
my_bool alloced;
#endif
} IO_CACHE_SHARE;
typedef struct st_io_cache /* Used when cacheing files */
{
/* Offset in file corresponding to the first byte of uchar* buffer. */
my_off_t pos_in_file;
/*The offset of end of file for READ_CACHE and WRITE_CACHE. For SEQ_READ_APPEND it the maximum of the actual end of file and the position represented by read_end. */
my_off_t end_of_file;
/* Points to current read position in the buffer */
uchar *read_pos;
/* the non-inclusive boundary in the buffer for the currently valid read */
uchar *read_end;
uchar *buffer; /* The read buffer */
/* Used in ASYNC_IO */
uchar *request_pos;
/* Only used in WRITE caches and in SEQ_READ_APPEND to buffer writes */
uchar *write_buffer;
/* Only used in SEQ_READ_APPEND, and points to the current read position in the write buffer. Note that reads in SEQ_READ_APPEND caches can happen from both read buffer (uchar* buffer) and write buffer (uchar* write_buffer). */
uchar *append_read_pos;
/* Points to current write position in the write buffer */
uchar *write_pos;
/* The non-inclusive boundary of the valid write area */
uchar *write_end;
/* Current_pos and current_end are convenience variables used by my_b_tell() and other routines that need to know the current offset current_pos points to &write_pos, and current_end to &write_end in a WRITE_CACHE, and &read_pos and &read_end respectively otherwise */
uchar **current_pos, **current_end;
/* The lock is for append buffer used in SEQ_READ_APPEND cache need mutex copying from append buffer to read buffer. */
mysql_mutex_t appe