Advanced Programming for UNIX environments: threads and fork

Source: Internet
Author: User
Tags mutex variables prepare printf thread

When the thread calls fork, a copy of the entire process address space is created for the child process. The child processes inherit the state of all mutexes, read-write locks, and condition variables from the parent process by inheriting copies of the entire address space. If the parent process contains more than one thread, the child process will need to clear the state of the lock if it is not immediately called Exec, after the fork returns.

There is only one thread inside the subprocess, consisting of a copy of the thread that invoked fork in the parent process. If a thread in the parent process occupies a lock, the child processes also occupy the locks. The problem is that the subprocess does not contain a copy of the thread that owns the lock, so the child process has no way of knowing which locks it occupies and which locks need to be freed.

When a multithreaded process calls fork to create a subprocess, pthreads specifies that only the thread that invokes fork exists within the child process (that is, only the calling thread is the thread in the child process). Although when returned from the fork call, only the calling thread exists in the subprocess, all other pthreads thread states (the state of the mutex, read-write locks and condition variables, and thread-private data keys) remain the same as they were when the fork was invoked. In a child process, the thread has the same state as within the parent process.

Note: The fork call does not affect the state of the mutex. If it is locked in the parent process, it is locked in the child process!

Because there is no call to the thread private data destroy and purge handler function, you may need to worry about the storage leak problem.

1.fork processor

int pthread_atfork (void (*prepare) (void), void (*parent) (void), void (*child) (void);//return value: Return 0 if successful, or return error number

Pthreads adds the Pthread_atfork "fork processor" mechanism to allow your code to bypass fork calls to protect data and invariants. This is similar to Atexit, which allows a program to perform cleanup operations when a process terminates.

See more highlights of this column: http://www.bianceng.cnhttp://www.bianceng.cn/OS/unix/

With pthread_atfork, you need to provide three separate processing function addresses. Prepare fork handlers are called before the parent process calls fork to create the subprocess, and the task of the fork handler is to obtain all the locks defined by the parent process. The parent fork handler is called in the parent process environment before the fork is created by the fork, and the task of the fork handler is to unlock all locks obtained by the prepare fork handler. The child Fork handler is invoked in the subprocess environment before the fork returns, and as with the parent fork handler, the Children fork handler must also release all locks acquired by the parent fork handler.

You can call Pthread_atfork to register multiple sets of callback functions more than once, and the order of callback function calls is set as follows:

The order of prepare function calls is the reverse of their registration order;

The parent and child functions are called in the same order as the registration order.

Sample code:

#include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include &  
lt;pthread.h> pthread_mutex_t lock1 = Pthread_mutex_initializer;  
      
pthread_mutex_t Lock2 = Pthread_mutex_initializer;  
    void Prepare (void) {printf ("Preparing locks...\n");  
    Pthread_mutex_lock (&AMP;LOCK1);  
Pthread_mutex_lock (&AMP;LOCK2);  
    void parent (void) {printf ("Parent Unlocking locks...\n");  
    Pthread_mutex_unlock (&AMP;LOCK1);  
Pthread_mutex_unlock (&AMP;LOCK2);  
    void Child (void) {printf (' Child Unlocking locks...\n ');  
    Pthread_mutex_unlock (&AMP;LOCK1);  
Pthread_mutex_unlock (&AMP;LOCK2);  
    } void *thr_fn (void *fn) {printf ("Thread started...\n");  
    Pause ();  
return 0;  
    int main (void) {pid_t pid;  
    pthread_t Tid; BSD systems and Mac OS systems do not support pthread_atfork #if defined (BSD) | | Defined (MACOS) printf ("Pthread_atforkis unsupported\n ");  
    #else Pthread_atfork (Prepare, parent, child);  
    Pthread_create (&tid, NULL, THR_FN, NULL);  
    Sleep (2);  
      
    printf ("Parent About to fork...\n");  
    PID = fork ();  
    if (0 = = pid) printf ("Child returned from fork\n");  
        else {printf ("Parent returned from fork\n");  
      Wait (NULL);  
#endif return 0; }

Run Result:

huangcheng@ubuntu:~$./a.out
thread started  
... Parent about to fork ...  
Preparing Locks  
... Parent Unlocking Locks  
... Parent returned from fork  
unlocking locks ...  
Child returned from fork

Author: csdn Blog Ctthuangcheng

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.