SQL Server Worker Threads为什么超过了max threads的设定值?

今天有客户写信问我, 他发现SQL server 的worker threads的总数超过了max worker threads的设定值, 不知道为什么会这样呢?他通过下面的语句得到worker thread 的总数:

 select COUNT(*)fromsys.dm_os_workers

上面的语句返回132:


 

然而max worker threads的设置是128:

select max_workers_count fromsys.dm_os_sys_info

返回128:

 

 这里,thread的总数是132,然而max worker配置是128,那么为什么会多出132-128=4个worker threads呢?

 答案就是worker threads的那个DMV里面包括了SQL server自己内部的一些worker threads。先看看下面的语句:

select scheduler_id,status, current_workers_count from sys.dm_os_schedulers

其中sys.dm_os_schedulers 会输出对应每个scheduler的所有worker threads,一个CPU一个scheduler。 上面语句输出如下:

你可以看到,sheduler id 为0~7对应的current_workers_count加起来正好128个,而对应id为257和255的scheduler的worker threads,加起来正好是4个。那么什么是hidden online的scheduer呢?去查下SQL server 联机手册,里面这样写的:

Indicates the status of the scheduler. Can be one of the following values:

  • HIDDEN ONLINE
  • HIDDEN OFFLINE
  • VISIBLE ONLINE
  • VISIBLE OFFLINE
  • VISIBLE ONLINE (DAC)
  • HOT_ADDED

Is not nullable.

HIDDEN schedulers are used to process requests that are internal to the Database Engine. VISIBLE schedulers are used to process user requests.

OFFLINE schedulers map to processors that are offline in the affinity mask and are, therefore, not being used to process any requests. ONLINE schedulers map to processors that are online in the affinity mask and are available to process threads.

DAC indicates the scheduler is running under a dedicated administrator connection.

HOT ADDED indicates the schedulers were added in response to a hot add CPU event.

 
所以HIDDEN的scheduler主要是SQL server自己使用的,最常用的就是备份backup了。 备份会使用HIDDEN scheduler。DAC表示那个专门给管理员连接使用的worker了。关于DAC可以参考联机手册。

 上面讨论的threads都是SQL server 自己create的。那么有什么方法能够知道除了SQL server 自己创建的threads外的threads呢?

有的。就是查询DMV sys.dm_os_threads. 此DMV有列started_by_sqlservr告诉您threads是否由SQL server 创建。下面的语句就列出那些非SQL server create的threads:

select *fromsys.dm_os_threadswhere started_by_sqlservr=0

结果如下: