Reentrant, asynchronous information security, thread safety

Source: Internet
Author: User
Tags mutex signal handler

These three concepts have been haunting me, I also occasionally will take out the discrimination, until yesterday only to find that they can straighten them out. So learning is such a repetitive process that eventually achieves the effect of epiphany. This article mainly refers to the third edition of the English version of Apue 10.6 and 12.5, as well as wiki Wikipedia, and csdn and StackOverflow in the discussion of these concepts, and then give a more reasonable understanding of their own.
?

I. Interrupts, signals, thread switching
    1. All of these three concepts involve asynchronous communication , where the running code is unpredictable when interrupts occur, when a signal is received, and when a thread switch occurs:

      • Interrupts, generally referred to as hardware interrupts, are hardware-to-CPU interrupts
      • Signal is a simulation of interrupts, which can be seen as an OS-to-process outage
      • Thread switching, CPU time-division multiplexing means
    2. Code Execution Flow:

#-表示代码在cpu上运行,.表示等待中##1. 中断和信号<f1>---------...................-----------<f2>.........-------------------...........###f1在执行的过程中被f2打断,当且仅当f2完整的执行完后返回f1##2. 线程切换<f1>----....----....----....----....----<f2>....----....----....----....----....###f1和f2互相打断彼此,交错地运行

?

II. reentrant, asynchronous information security, thread safety 1. Can be re-entered

Reentrant means that a function is not finished and is called once in another place , and two calls can get the correct result. The reentrant concept already existed before the multitasking operating system, and It is a concept from the time when no multitasking operating systems existed.

2. Asynchronous information security, thread safety

The "Other place" mentioned in the reentrant can be:

    • In this case, if the function is reentrant in the interrupt or signal, it is called the asynchronous signal is safe , and These two cases can be considered as a recursive invocation . The APUE10.6 section is designed to describe the safety of asynchronous signals.
    • In another thread, in this case if the function is reentrant, it is called a thread-safe function. The APUE12.5 section is dedicated to thread safety.

If a function is reentrant with respect to multiple threads, we say the It is thread-safe. This doesn ' t tell us, however, whether the function was reentrant with respect to signal handlers. We say that a function, which is safe to being reentered from the asynchronous signal handler is async-signal safe. -according to Apue 3e Chapter 12.5

3. The relationship between the three

The more reasonable diagram of the three should be:
               
Red indicates a non-reentrant function, and a+b+c represents a reentrant function where A is reentrant in the case of recursive calls, C is reentrant in the case of multithreading, and B is reentrant in all cases. So it is meaningless to say that a function is re-entered without qualifying the scene, and that it is meaningful to just say that it is non-reentrant ...

4. List of asynchronous signal security functions

  

5. Common Puzzles FAQ
    • Q: are thread-safe functions reentrant?
      A: Thread-safe functions are reentrant in multithreaded situations. But it is not reentrant in the case of a signal or interrupt. Examples are as follows:
      A function that uses the mutex mechanism to achieve multithreading security, if used in a signal processing function, then there may be a deadlock, so it is not asynchronous signal security.

    • Q: Can the Reentrant function and the asynchronous signal security function be equal?
      A: According to the above diagram can be concluded that the two are not equal, reentrant function in different scenarios can be divided into asynchronous signal security and thread safety. Asynchronous signal security can be considered as reentrant in the case of recursive invocation. Examples are as follows:

//非可重入版本int t;void swap(intint *y){    t = *x;    *x = *y;    // hardware interrupt might invoke isr() here!!    *y = t;}void isr(){    int12;    swap(&x, &y);}
//异步信号安全版本,非线程安全int t;void swap(intint *y){    int s;    // save global variable    t = *x;    *x = *y;    // hardware interrupt might invoke isr() here!    *y = t;    // restore global variable}void isr(){    int12;    swap(&x, &y);}
    • Q: Are there any other questions?
      A: No, the above explanation is clear enough, haha
      ?
Iii. It's the jade of mountain
  1. The signal, like a hardware interrupt, interrupts the sequence of instructions being executed. The signal processing function cannot determine where the process is running when the signal is captured. If the operation in the signal processing function is the same as that of the interrupted function, and there is a static data structure in the operation, when the signal processing function returns (of course, the signal processing function can be returned), the original execution sequence is restored, May cause operations in the signal processing function to overwrite data in the previous normal operation.
    Therefore, the reason why the function is not reentrant is:

    • The function uses static data structures;
    • The function calls malloc and free. Because malloc typically maintains a linked table for the allocated store, while inserting the execution signal handler, the process may be modifying the linked table;
    • functions are standard IO functions because many implementations of the standard IO libraries use global data structures;
    • function modifies its own code, resulting in multiple calls to different code;
    • Wait a minute.
  2. Even for reentrant functions, it is important to note that the errno is a problem to use in signal processing functions. There is only one errno variable in a thread, and the reentrant function used in the signal processing function may also modify the errno. For example, the Read function is reentrant, but it is also possible to modify errno. Therefore, the correct approach is to start with the signal processing function, save the errno first, when the signal processing function exits, and then restore the errno.
    For example, the program is calling printf output, but when you call printf, a signal appears, and the corresponding signal handler has a printf statement, which results in a mix of two printf outputs.
    If it is for printf locking, the same situation as above will lead to deadlock. In this case, the method used is usually to shield certain signals in a particular area.
    Method of shielding the signal:
    1> signal (sigpipe, sig_ign); Ignoring some signals
    2> Sigprocmask ()
    Sigprocmask is defined only for single threads
    3> Pthread_sigmask ()
    Pthread_sigmasks can be used in multiple threads

  3. Many functions are not thread-safe, because the data they return is stored in a static memory buffer. By modifying the interface, the caller provides the buffers themselves to make these functions thread-safe. When the operating system implements support for thread-safe functions, some of the non-thread-safe functions in posix.1 are provided with replaceable thread-safe versions.
    For example, gethostbyname () is thread insecure and provides a thread-safe implementation of Gethostbyname_r () in Linux.
    The function name is appended with "_r" to indicate that this version is reentrant (for thread reentrant, that is, thread-safe, but not for signal processing functions that are reentrant or asynchronous).

  4. Common negligence problems in multi-threaded programs

    • Passing the pointer as a parameter to the new thread to call Fang, I've made such a mistake ...
    • A share that accesses global memory without the synchronization mechanism protection can change state.
    • A deadlock occurs when two threads attempt to take the same permissions on the global resource in turn. One of the threads controls the first resource, and another thread controls the second resource. None of the threads can continue to operate until one of the threads has been discarded.
    • Try to regain the held lock (recursive deadlock).
    • Create hidden intervals in sync protection. This interval will occur in protection if the protected code snippet contains functions that release the synchronization mechanism and regain the synchronization mechanism before returning the caller. The results are misleading. For callers, the global data is protected from the surface, but is not actually protected.
    • When mixing UNIX signals with threads, use the sigwait (2) model to process asynchronous signals.
    • Call setjmp (3C) and longjmp (3C) and then jump for a long time without releasing the mutex.
    • The condition cannot be re-evaluated when returned from a call to *_cond_wait () or *_cond_timedwait ().
  5. If a function is reentrant for multiple threads, the function is thread-safe, but this does not mean that the function is reentrant for the signal handler.
    If the function is safe to re-enter the asynchronous signal handler, then it can be said that the function is "asynchronous-signal safe".
    ?

Iv. reference Documentation
    1. Apue Third edition of the original 10.6&12.5, to read the original instead of the Chinese version (Youdao in the hand, the world I have: P)
    2. Https://en.wikipedia.org/wiki/Reentrancy_ (computing)
    3. http://bbs.csdn.net/topics/310140183
    4. Http://stackoverflow.com/questions/9837343/difference-between-thread-safe-and-async-signal-safe
    5. Http://stackoverflow.com/questions/18198487/are-r-unix-calls-reentrant-async-signal-safe-thread-safe-or-both

Reentrant, asynchronous information security, thread safety

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.