Vector 与 pthread_create 线程函数的使用注意事项
1. 宏定义与 Vector 初始化
尝试使用宏定义配合 Vector 初始化时需注意语法规范。
#define MAXTHREADS 200
// 错误写法:宏后直接跟变量声明可能导致解析错误
// vector<string> m_vec(MAXTHREADS);
若定义数组则通常可行:
#define MAXTHREADS 200
string vec[MAXTHREADS];
2. 类成员函数作为线程入口
在 C++ 中,类的成员函数不能直接作为 pthread_create 的线程函数,因为成员函数隐含了 this 指针,而线程函数签名固定为 void* (*)(void*)。
3. 线程函数内访问 Vector
3.1 类成员 Vector 报错
若在静态线程函数中直接访问类成员,会因缺少对象实例导致编译错误。
class T {
vector<string> m_vector;
};
static void* threadfun(void* param) {
// 错误:无法直接访问非静态成员
// T::m_vector[0];
// 正确:需通过参数传递对象指针
T* pthis = static_cast<T*>(param);
pthis->m_vector[0];
}
3.2 全局 Vector 访问
若 Vector 定义在类外(全局),需确保链接可见性。
vector<string> m_vec(200);
class T {}
static void* threadfun(void* param) {
string tmp = "rdm";
m_vec[id] = m_vec[id] + tmp;
}
若出现 Link 失败,通常是因为符号未定义或作用域问题。

