C++ 多线程
Hello pThread
步骤以及知识点
1:引入头文件 pthread.h
2:pthread_create (thread, attr, start_routine, arg) //创建线程
参数说明:
thread:指向线程标识符指针。
attr:一个不透明的属性对象,可以被用来设置线程属性。您可以指定线程属性对象,也可以使用默认值 NULL。
start_routine:线程运行函数起始地址,一旦线程被创建就会执行。
arg:运行函数的参数。它必须通过把引用作为指针强制转换为 void 类型进行传递。如果没有传递参数,则使用 NULL。
3:pthread_exit (status) //终止线程
pthread_exit 用于显式地退出一个线程。通常情况下,pthread_exit() 函数是在线程完成工作后无需继续存在时被调用。
如果 main() 是在它所创建的线程之前结束,并通过 pthread_exit() 退出,那么其他线程将继续执行。否则,它们将在 main() 结束时自动被终止。
开始之前:vs2017无法打开源文件pthread.h
一般来说win下玩多线程之前都会有这个问题,因为pthread这个库是linux下的库。所以我们需要再windows下也去装下这个库。这里特地记录下如何解决。传送门:https://blog.csdn.net/user11223344abc/article/details/80536280
然而…在解决了这个问题之后,我发现,c++ 11 之后有了标准的线程库——#include thread。但是这个库我没去使用,因为我们主要是android方面,所以还是以这个Posix标准下的pthread为准。
创建线程-pthread_create
/*
* PThread Functions
*/
PTW32_DLLPORT int PTW32_CDECL pthread_create (pthread_t * tid,
const pthread_attr_t * attr,
void *(PTW32_CDECL *start) (void *),
void *arg);
//params
pthread_t * tid:创建的线程id
const pthread_attr_t * attr:线程参数
void *(PTW32_CDECL *start) (void *):调用的函数
void *arg:传入的函数参数
函数分析:
tid类型为:pthread_t *
pthread_t:
↓
那么pthread_t是啥?
typedef ptw32_handle_t pthread_t;
↓
pthread_t是个结构体:这个结构体包含2个字段
typedef struct {
void * p; /* Pointer to actual object */
unsigned int x; /* Extra information - reuse count etc */
} ptw32_handle_t;
void * 参考:https://blog.csdn.net/user11223344abc/article/details/80524964
终止线程-pthread_exit
函数原型:
PTW32_DLLPORT void PTW32_CDECL pthread_exit (void *value_ptr);
代码流程
1.pthread_t tids[NUM_THREADS];//创建5个线程id,数组形式。
2.for循环创建5个线程,调用pthread_create。
3.pthread_create传参,第一个参数不用说,pthreadid数组遍历取地址扔里边即可。
4.pthread_create传参,第二个参数是说线程参数,目前我们还不知道这个具体有啥用,先丢个NULL进去。
5.pthread_create传参,第三个和第四个参数,执行方法编写,执行方法的参数定义。 (这个参数类型是void (PTW32_CDECL *start) (void ),这种形式的类型还是第一回见)。
另外需要注意的是:传递进去的方法是这种形式。为什么是这种形式?我想可能是因为void指针可以指向任意类型的数据吧。
void * testSay(void *) {
void * p;
return p;
}
5.ret作为线程的返回值,当不为0时,表示异常。