How MySQL’s KILL Command Terminates Threads: Diagrams & Code Explained
This article explains how MySQL processes the KILL command, detailing the interaction between threads, the role of the kill flag, and the is_killed() function, all illustrated with diagrams and code examples to help readers grasp thread termination internals.
This is the second article in my diagram series. We explore how MySQL uses the KILL command to terminate threads, as shown in the diagram, and provide examples to help you understand.
Many people think they understand this topic, but they often do not or have misconceptions. The KILL operation is not handled by the thread that runs the KILL command; instead, the thread being terminated handles it, which can be confusing, so a diagram helps clarify.
The diagram shows the interaction between two threads:
Thread ID 10 is the worker thread actively executing a query.
Thread ID 12 issues KILL 10 to terminate thread ID 10.
Thread 10 : The thread enters a loop processing query chunks. For operations like ORDER BY, GROUP BY, or ALTER TABLE, it reads row blocks, processes them, and checks the thd_killed() flag after each block to decide whether to continue or terminate.
Thread 12 : This thread sends the KILL command, using the function thd_set_kill_status() to set the termination flag for thread 10.
Kill flag behavior:
If the termination flag is not set ( thd_killed()=0), thread 10 continues processing. If the flag is set ( thd_killed()=1), query execution stops, temporary tables are discarded, and all active transactions are rolled back.
MySQL Function: is_killed()
The function is_killed() checks whether a thread should be terminated:
bool Sql_data_context::is_killed() const {
const auto kill = thd_killed(get_thd());
DBUG_LOG("debug", "is_killed:" << kill);
if (0 == kill) return false;
return ER_QUERY_INTERRUPTED != kill;
}If kill == 0, the thread continues running; otherwise, the thread is interrupted and stops further execution.
Conclusion
By understanding the KILL command and how MySQL manages thread lifecycles, you can see why it may take longer than expected. Always carefully examine your queries and avoid indiscriminately killing threads in production, as this can disrupt critical operations. Safety is better than regret.
Aikesheng Open Source Community
The Aikesheng Open Source Community provides stable, enterprise‑grade MySQL open‑source tools and services, releases a premium open‑source component each year (1024), and continuously operates and maintains them.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
