What is an interrupt


Interrupt is actually an “interrupt” event. What exactly does an interrupt meanContext contextandWith reference to the objectWho is it. Considering events, we can simply abstract interrupts into a model like this:

When we analyze certain interrupt events, we need to be aware of these four objects:

The interrupt source

  • Who is the interrupt source
  • Under what conditions does an interrupt source trigger an interrupt
  • How is the interrupt source triggered

Interrupt signal

  • What exactly does the signal refer to
  • Whether the signal needs to be stored
  • How to store

Interrupt controller

  • Interrupt signal management

For example, whether the signal sent by the interrupt source is shielded, whether the signal can be processed repeatedly by the interrupt processor, whether the signal processing has priority…

Interrupt handler

  • How do you get the signal
  • What do you do when you get the signal
  • What do you do after processing the signal

These four types of objects are not always present in the actual interrupt event, and may be more complex or simpler. But when we consider interrupt events, we need to make it clear that “objects” with similar functionality should take on such logic.

Below we mainly around the operating system interrupt mechanism, Java interrupt mechanism, how to design an asynchronous thread interrupt system these three parts of a simple discussion.

Interrupt mechanism of operating system


The interrupt related to the operating system usually refers to the process of temporarily suspending the running of the current program on the CPU when an urgent event is encountered during the execution of the program, and then switching to the execution of the corresponding event handler. After the processing is completed, the original program is interrupted or other programs are scheduled to execute.

According to the difference of interrupt event itself, it can be divided into interrupt event outside processor, exception, system exception.

Interrupt events outside of the processor

An interrupt event caused by a signal from a peripheral device that is not related to the current running instruction. The schematic diagram is as follows:

Let’s look at the above four objects respectively:

  • The interrupt source

Interrupt source: external device, such as printer, keyboard, mouse, etc.

Trigger conditions: such as I/O interruption reported by peripheral devices in I/O status; The corresponding signal interruption issued by peripheral devices, such as clock interruption, keyboard/mouse corresponding signal interruption, shutdown/restart interruption, etc.

Trigger mode: The external device sends an interrupt request IRQ to the interrupt controller.

  • Interrupt signal

That is, what the interrupt source tells the interrupt controller.

It can generate a specific level on a signal line (using high and low level to indicate whether to interrupt two states), it can also send a specific message or message sequence on the bus, and it can also set the interrupt state that has occurred in the interrupt register.

  • Interrupt controller

A control unit in a CPU that includes interrupt control logic lines and interrupt registers. Responsible for interrupt discovery and response.

That is to say responsible for checking the interrupt signal in the interrupt register, when the interrupt is found to switch the CPU current process program, to deal with the interrupt program. The response diagram is as follows:

  • Interrupt handler

This refers to how the CPU receives different interrupt signals. This section includes Interrupt Processing and Resume Normal Operations.

1. Interrupt the process

First, THE CPU needs to save the context of the current running process, analyze THE PSW from the interrupt process, determine the corresponding interrupt source and execute the corresponding interrupt handler.

Tip: PSW (Program Status Word): An area of memory or hardware in a computer that contains information about the Status of programs used by the operating system. A special register is usually used to indicate processor state. It can be understood as the interrupt signal storage device we mentioned above.

2. Restore normal operations

When the interrupt program is executed, which process to execute next is determined by the process scheduling, and the scheduling policy determines whether to schedule the process before the interrupt execution.

The relatively complete interrupt response flow chart is as follows:

The two kinds of interrupt events, exception and system exception, mainly belong to the interrupt events caused by the execution of specific instructions by the processor. Different from the interrupt source of the interrupt event caused by the hardware peripherals, the initiation, control and processing of the interrupt are mainly undertaken by the operating system’s instruction logic and circuit. Is a synchronous processing operation, while an external interrupt is initiated by an external device, which is an asynchronous processing operation. Let’s give a brief introduction.

abnormal

An exception is an interrupt event caused by the current running instruction. Including fault caused by error conditions, such as division by zero arithmetic error, page missing exception; Also includes terminations caused by unrecoverable fatal errors, usually some hardware error.

  • Exception handling

forThe faultDepending on whether the fault can be recovered, the fault handler either reexecutes the instruction that caused the fault or terminates.

forTermination ofThe handler returns control to an ABORT routine, which terminates the application.

A system exception

System exception refers to the interrupt event caused by system call triggered by executing the trap instruction, such as request device, request I/O, create process, etc.

  • System call handling

Such intentional exceptions are calledtrapTo deal with. After processing is complete, the trap program returns control to the next instruction in the application control flow.

To summarize, the operating system’s interrupt class behavior is as follows:

Well, big Head is done. Since little Sister is mainly Java code farmers, the following will mainly introduce what interrupt semantics are related to Java.

Java interrupt mechanism


After understanding the above operating system interrupts, Java’s interrupt mechanism is easy 😀

Interrupts in Java are when thread A sends an interrupt signal to thread B, which then decides how to respond based on the interrupt handling logic in its currently executing program. Well, it’s that simple

Let’s examine the “four objects” in interrupt events a bit:

  • The interrupt source

Interrupt source: thread A

Interrupt trigger condition: thread A determines

How interrupt sources are triggered: The threadB#interrupt() method is called in thread A.

It’s not hard to implement the mechanics, but let’s think about two questions before we start talking nonsense:

Q:

Question 1: How do threads communicate with each other? How can interrupt signals from thread A be transmitted to thread B?

Question 2: The thread states are Running, Blocked, Waiting, etc. When thread B is in different states, how does it respond to the interrupt signal?

A:

Problem 1: In this case it is ok for threads to communicate with each other in shared memory. All you need to do is set each thread to an interrupt bit, so that thread A calls threadB#interrupt() and sets threadB’s interrupt bit to true. The signal gets through

Problem 2: When thread B is in the non-blocking state, thread B can determine whether the interrupt flag is true at the place where it needs to process the interrupt logic, and then respond to process the interrupt.

But when thread B is blocked, how the hell does it check its interrupt flag?

The JVM helps when thread B blocks Object#wait(),Thread#join(),Thread#sleep(), and implements InterruptibleChannel IO and Selector select(). The JVM causes thread B to throw an exception or wake up immediately, giving thread B the option of responding to an interrupt or not.

Because it is the Interrupt mechanism implemented in Java, the interrupt flag setting is also done by the JVM.

  • Interrupt signal

Signal: Interrupt flag of a thread.

Storage: JVM rules.

  • Interrupt controller

The JVM controls how the signal is stored and wakes up thread B in time. Thread B controls its own interrupt response logic, when to respond and how to respond.

  • Interrupt handler

Get a signal: the threadB finds out if it has been interrupted by calling threadB#isInterrupted(), polling the signal itself.

How to handle signals: Thread B decides.

What to do after processing the signal: thread B decides.

Java’s thread interrupt mechanism is designed to be flexible, allowing the user to decide what to do with the interrupt.

To summarize the Java interrupt related methods:

In the JDK, the ThreadPoolExecutor#shutdownNow() method of the thread pool calls the interrupt() method of each worker thread in the workers thread array to shutdown the thread pool.

The thread pool does not know the interrupt execution status of worker threads. If the worker thread ignores the interrupt signal, the current task may still be executed and unexpected results may occur.

Design an interrupt system between asynchronous threads


Let’s look at the Interrupt mechanism in Java. It just provides thread A to send interrupt signals to thread B.

  • Thread A does not know the result of thread B’s interrupt processing.
  • If thread A can’t get thread B’s thread object, it can’t send an interrupt signal.

Consider this scenario: When we perform a large task, Task1, it is too large. We split it into Task2 and Task3 and threw it into a thread pool. They are also large, so we split them up into Task4, Task5, Task6, Task7, and throw them into the thread pool again.

If we want to cancel the execution of task1, how can we ensure that all workers in the figure can cancel the execution of the corresponding task successfully?

  • Demand analysis

When we cancel Task1, what we want to do is to cancel all tasks and get cancellation results for all tasks.

Why emphasize tasks? Because workers may not only work for one task… The task2 worker, for example, drops Task4 and Task5 into the thread pool and is done. If we change the cancel task1 to the cancel task1 worker thread, it may cause the non-Task1 program currently running on the worker thread to fail.

It is not easy to know which thread all tasks are currently running on. We also need to know the results of all tasks.

  • Design ideas

Java’s interrupt mechanism alone won’t suffice, but we can learn from it:

1. It uses interrupt flags to record whether a thread should be interrupted

2. Throw an exception when a thread is blocked

What we want to stop is the execution of all task programs, so we need to design interrupt flag bits strongly bound to task, which can have four states: uninterrupted, interrupted, interrupted success, and interrupted failure. To make it accessible to all threads, define a global shared variable.

The interrupt source and the interrupt handler communicate with each other through the interrupt flag bit of the task. If the thread running the task is blocking, how do you wake it up to determine the interrupt status?

For our scenario, it is difficult to know who the blocking thread is currently running the Task. All you can do is insert multiple interrupt detection points so that when the blocking thread wakes up, it can determine the interrupt flag again and respond to the interrupt.

The other:

Only Java’s interrupt mechanism can wake up a thread, but if the current worker is not a thread pool you can manage, its interrupt handling logic cannot be controlled.

If you can control all workers running tasks and workers get results synchronously while executing tasks. This can be done by combining the interrupt flag, which is strongly bound to the task, with the Java interrupt mechanism, where the former serves more as a function of getting the interrupt result of the task.

Afterword.


  • The “event processing” scenario has a lot in common with thread pools, message-oriented middleware, streaming processing, etc., such as how to guarantee exactly once of events, push-pull model, scheduling, etc.

  • In writing this article, especially the operating system interrupt mechanism, little sister is also learning to sell, and referred to most of the material. I also asked my friends to help me point out any misunderstanding or difficulty in the article, so that we could communicate and make progress together.

  • The final technical section discusses “how to design an interrupt system between asynchronous threads”, which is a problem little Sister is currently encountering in her work. The problem is similar to canceling tasks with the task scheduling component, except that we do not currently manage all the task worker threads with the task scheduling component. If your partner has a better plan, please inform your sister.


Finally, talk about a small thing in life ~

Recently little sister discovered a treasure in station B. In his latest video, he talked about Yu Hua’s “To Live”. There is such a joke in the book that made the little sister cry, imitating it to you 😀

One by one came in conveniently point a concern. 22 jun could not help but send a look, 33 sauce feel so good little sister how to help share to the circle of friends. Jun sauce I see you appreciate, to come to also so polite why ~

Prove that you are not a person, one after another, save the little sister 🙂

Resources: [1]. www.icourse163.org/course/NJU-.

[2]. In-depth Understanding of Computer Systems

[3]. www.zhihu.com/question/47.

[4].zhuanlan.zhihu.com/p/26524241