《APUE》:线程和fork


《Unix环境高级编程》这本书附带了许多短小精美的小程序,我在阅读此书的时候,将书上的代码按照自己的理解重写了一遍(大部分是抄书上的),加深一下自己的理解(纯看书太困了,呵呵)。此例子在Ubuntu10.04上测试通过。

程序简介:多线程的进程通过fork函数创建子进程时,如果要清除各种锁的状态,可以通过调用pthread_atfork函数建立fork处理程序。

  1. //《APUE》程序12-7:pthread_atfork实例   
  2. #include <stdio.h>   
  3. #include <stdlib.h>   
  4. #include <unistd.h>   
  5. #include <signal.h>   
  6. #include <pthread.h>   
  7.   
  8. pthread_mutex_t lock1 = PTHREAD_MUTEX_INITIALIZER;  
  9. pthread_mutex_t lock2 = PTHREAD_MUTEX_INITIALIZER;  
  10.   
  11. void prepare(void)  
  12. {  
  13.     printf("preparing locks...\n");  
  14.     pthread_mutex_lock(&lock1);  
  15.     pthread_mutex_lock(&lock2);  
  16. }  
  17.   
  18. void parent(void)  
  19. {  
  20.     printf("parent unlocking locks...\n");  
  21.     pthread_mutex_unlock(&lock1);  
  22.     pthread_mutex_unlock(&lock2);  
  23. }  
  24.   
  25. void child(void)  
  26. {  
  27.     printf("child unlocking locks...\n");  
  28.     pthread_mutex_unlock(&lock1);  
  29.     pthread_mutex_unlock(&lock2);  
  30. }  
  31.   
  32. void *thr_fn(void *fn)  
  33. {  
  34.     printf("thread started...\n");  
  35.     pause();  
  36.     return 0;  
  37. }  
  38.   
  39. int main(void)  
  40. {  
  41.     pid_t pid;  
  42.     pthread_t tid;  
  43.     //BSD系统和MAC OS系统不支持pthread_atfork   
  44. #if defined(BSD) || defined(MACOS)   
  45.     printf("pthread_atfork is unsupported\n");  
  46. #else   
  47.     //见注解2   
  48.     pthread_atfork(prepare, parent, child);  
  49.     pthread_create(&tid, NULL, thr_fn, NULL);  
  50.     sleep(2);  
  51.     printf("parent about to fork...\n");  
  52.   
  53.     pid = fork();  
  54.     if( 0 == pid )  
  55.         printf("child returned from fork\n");  
  56.     else  
  57.         printf("parent returned from fork\n");  
  58. #endif   
  59.   
  60.     return 0;  
  61. }  

运行示例(红色字体的为输入):

www.bkjia.com @ubuntu:~/code$ gcc temp.c -lpthread -o temp
www.bkjia.com @ubuntu:~/code$ ./temp

thread started...
parent about to fork...
preparing locks...
parent unlocking locks...
parent returned from fork
child unlocking locks...
child returned from fork

注解:
1:父进程通过fork创建了子进程。子进程不但继承了父进程整个地址空间的副本,也继承了所有的互斥量,读写锁和条件变量的状态,如果父进程包含多个线程,子进程在fork返回之后,如果不是紧接着使用exec的话,就要清理锁状态。
2:pthread_atfork最多可以安装三个帮助清理锁的函数。prepare函数将在fork创建子进程之前被调用,通常可以用来获取进程中的所有锁;parent在fork创建子进程后返回前在父进程中被调用,可以用来释放父进程中的锁;child在fork创建子进程后fork返回前在子进程中被调用,可以用来释放子进程中的锁。给这三个参数传递NULL,表示不调用该函数。

相关内容