文章目录
本文的环境:
Linux centos-7.shared 3.10.0-693.5.2.el7.x86_64 #1 SMP Fri Oct 20 20:32:50 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
gcc 版本 4.8.5 20150623 (Red Hat 4.8.5-39) (GCC)
本文使用 POSIX 线程库,需引入头文件 pthread.h
,在编译的时候要注意添加 -lpthread
参数。
POSIX 是一个标准,约定一个操作系统应该提供哪些接口,pthread 即为 posix thread。C++11、Python、Java 均内置了线程库。
线程创建
int pthread_create(
pthread_t *thread,
const pthread_attr_t *attr,
void *(*start_routine) (void *),
void *arg
);
参数:
thread 是一个输出型参数,返回一个线程 id。
attr 可以设置线程属性,填 NULL 表示使用默认属性。
start_routine 是一个函数指针,是线程执行的入口函数。
arg 是 start_routine 的函数参数。
值得注意的是这个函数 arg 是不支持传递多个参数的(可变参数),如果需要传递多个函数就需要使用 struct 或者一些别的方式。
返回值:
成功返回 0,失败返回错误码。
栗子:
创建一个线程,传递一个参数,并在这个新线程内打印这个参数。
#include <stdio.h>
#include <unistd.h>
#