linux多线程编程中用到的函数和类型

来源:互联网 发布:物流软件制作 编辑:程序博客网 时间:2024/05/16 00:28

1. pthread_fork()

#include <pthread.h>int pthread_atfork(void (*prepare)(void), void (*parent)(void), void (*child)(void)); /*Description:The pthread_atfork() function shall declare fork handlers to be called before and after fork(), in the context of the thread that called fork(). The prepare fork handler shall be called before fork() processing commences. The parent fork handle shall be called after fork() processing completes in the parent process. The child fork handler shall be called after fork() processing completes in the child process. If no handling is desired at one or more of these three points, the corresponding fork handler address(es) may be set to NULL.Return ValueUpon successful completion, pthread_atfork() shall return a value of zero; otherwise, an error number shall be returned to indicate the error.*/

fork可能是在主线程中调用,也可能实在子线程中调用,
fork得到一个新进程,新进程只有一个执行序列,即只有一个线程(调用fork的线程被继承下来)
实际上,对于编写多线程程序来说,最好不要再调用fork
不要编写多线程多进程程序,要么用多线程,要么用多进程。

2. __thread

参考:https://gcc.gnu.org/onlinedocs/gcc-4.2.4/gcc/Thread_002dLocal.html
http://blog.csdn.net/liuxuejiang158blog/article/details/14100897

gcc内置的线程局部存储设施,__thread 修饰的变量是线程局部存储的。(两个下划线),只能修饰POD类型(即C兼容的原始数据类型)。

例如:

     __thread int i;     extern __thread struct state s;     static __thread char *p;

3. pthread_once()

参考:http://linux.die.net/man/3/pthread_once

pthread_once()函数,在多线程中,保证某个函数只被执行一次。#include <pthread.h>

#include <pthread.h>/** The first call to pthread_once() by any thread in a process, with a given once_control, * shall call the init_routine with no arguments. Subsequent calls of pthread_once() with * the same once_control shall not call the init_routine. */int pthread_once(pthread_once_t *once_control, void (*init_routine)(void));pthread_once_t once_control = PTHREAD_ONCE_INIT; 

4. atexit()

参考:http://man7.org/linux/man-pages/man3/atexit.3.html

#include <stdlib.h>/** atexit  - register a function to be called at normal process termination* 注册一个函数,在程序终止时执行。*/int atexit(void (*function)(void));
0 0
原创粉丝点击