C++/C本身并没有多线程的内容,需要使用pthread库, include<pthread.h>,编译+ -lpthread, pthread是一个posix标准,在不同平台上有不同实现,这里以linux pthread库为准.
参考https://computing.llnl.gov/tutorials/pthreads/#CreatingThreads
一,线程的创建
1,使用pythread_create函数,原型如下
int pthread_create(pthread_t* thread,const pthread_attr_t * attr, void*(*start_routine)(void*), void *restrict args);
参数 thread: pthread_t 类型的指针,相当于一个线程id
attr: 线程属性 pthread_attr_t类型,一般可以填NULL
start_routine: 线程入口函数, 必须返回void* 且有一个 void* 类型的参数
args 传给入口函数的参数, void*类型
2,如果要传入多个参数,可以用一个struct把参数包起来,传给入口函数,再用类型转换转成struct
3,如果想知道自己的线程号可以用pthread_self()
二线程的join和detach
1, join的含义是调用join的线程会一直block直到被join线程结束, 线程需要有joinable属性才能被join,否则就是detach的, 显然这么做的原因是join需要一定的开销.
2,join函数; int pthread_join(pthread_t thread, void **retval);