Innodb 后台线程

184 阅读3分钟

本文正在参加「技术专题19期 漫谈数据库技术」活动

Innodb 有两个核心的功能模块,后台线程和内存,Innodb本身是基于磁盘存储的引擎,所以需要使用内存来做缓存等其他功能,那么这种情况下,从MySQL到内存,从内存到磁盘就需要一系列的功能,这些功能被集中在后台线程当中,所以后台线程是为了刷新内存池当中的数据,保证内存池当中缓存的数据是最新的,并且将内存池当中的数据刷新到磁盘上,今天聊聊Innodb后台线程的分类和功能。

Master线程

这个是最为核心的后台线程,负责了讲缓存池当中的数据异步刷新到磁盘,保证数据一致性,包括脏页刷新,合并插入缓存,UNDO页面回收等,但是也由于master线程负责的东西太多了,使用的效率变低,在Innodb的版本更新当中,逐渐的将Master线程负责的部分功能创建新的线程来完成。

IO线程

Innodb在处理数据当中,免不了从磁盘取出数据和将数据缓存回磁盘的操作,这样IO操作很浪费性能,所以Innodb采用了AIO(async IO)来处理IO操作,IO线程主要是为了处理AIO的回调函数,IO线程包括四种:write, read, insert buffer, log,我们可以通过命令来看:

mysql> show engine innodb status \G;
*************************** 1. row ***************************
  Type: InnoDB
  Name:
Status:
=====================================
2022-11-18 06:22:00 0x1f74 INNODB MONITOR OUTPUT
=====================================
........
--------
FILE I/O
--------
I/O thread 0 state: wait Windows aio (insert buffer thread)
I/O thread 1 state: wait Windows aio (log thread)
I/O thread 2 state: wait Windows aio (read thread)
I/O thread 3 state: wait Windows aio (read thread)
I/O thread 4 state: wait Windows aio (read thread)
I/O thread 5 state: wait Windows aio (read thread)
I/O thread 6 state: wait Windows aio (write thread)
I/O thread 7 state: wait Windows aio (write thread)
I/O thread 8 state: wait Windows aio (write thread)
I/O thread 9 state: wait Windows aio (write thread)
Pending normal aio reads: [0, 0, 0, 0] , aio writes: [0, 0, 0, 0] ,
 ibuf aio reads:, log i/o's:, sync i/o's:
Pending flushes (fsync) log: 0; buffer pool: 0
457 OS file reads, 53 OS file writes, 7 OS fsyncs
0.00 reads/s, 0 avg bytes/read, 0.00 writes/s, 0.00 fsyncs/s
........
​
ERROR:
No query specified

这里可以看到有1个insert buffer IO线程,1个log io线程,4个read IO 线程和write IO线程。

Purge 线程

MySQL事务具有原子性,事务包含的所有操作要么全部成功,要么全部失败回滚,因此事务的操作如果成功就必须要完全应用到数据库,如果操作失败则不能对数据库有任何影响,为了保证这一点,在事务执行的过程当中,会生成undo log来保证执行失败回滚数据库,比如,插入执行一般,已经插入了id,但是其他部分执行失败了,那么就要通过undo log回滚数据库到没有插入之前。

但是当事务执行完成,undo log就没有用了,所以需要进行回收,在之前的版本(大约是1.1版本),这个工作是有master 线程完成的,后来为了减轻Master线程工作,提高CPU使用率,单独的分出了purge线程来处理undo log。

mysql> show variables like 'innodb_purge_threads' \G;
*************************** 1. row ***************************
Variable_name: innodb_purge_threads
        Value: 4
1 row in set, 1 warning (0.00 sec)
​
ERROR:
No query specified

有四个purge 线程。

Page cleaner 线程

这个也是新版本出现的一个线程类型,也是为了分担master线程的压力,提高cpu使用率和引擎性能的线程,主要负责Master线程负责的脏页刷新操作。

嗯,Innodb的线程分类就聊这么多,之后想详细的聊聊AIO这些实现的细节技术点,还是请大佬们多多指点。

本文正在参加「技术专题19期 漫谈数据库技术」活动