编程技巧

关于线程创建函数pthread_create

#include<pthread.h>

int pthread_create(pthread_t *tidp, const pthread_attr_t *attr, void *(*start_rtn)(void*), void *arg);

// 第一个参数为指向线程标识符的指针
// 第二个参数用来设置线程属性
// 第三个参数是线程运行函数的起始地址
// 第四个参数是运行函数的参数

在多线程编程中,当pthread_create函数调用类成员函数在新创建的线程中运行时,被调用的成员函数必须为静态成员函数。这是因为非静态成员函数会自动返回this指针指,并传入pthread_created。此种行为将导致pthread_created函数的输入与形参不匹配。而静态成员函数没有this指针,故可以传入pthread_create函数。但由于静态成员函数不能调用类中非静态成员,若想在新线程中运行的函数内使用非静态成员,需要将this指针作为参数传递给此静态成员函数,如此便可通过this指针在静态成员函数中调用非静态成员。具体的说,是通过pthread_create函数的第四个参数,将this指针传入新线程中的函数。但需要注意将this指针类型强制转换为void *类型,同时也要在传入pthread_create的函数的设计过程中考虑其形参与返回值类型应该与pthread_create的输入要求相符合。

posted @ 2020-10-30 10:15  溪嘉嘉  阅读(113)  评论(0编辑  收藏  举报