如何调用在main中定义的另一个函数中的线程
How to call a thread inside another function and defined in main?
我正在编写c++代码。现在我对线程函数或基本c++概念感到困惑。我有一个头文件,一个函数文件和一个主函数文件。
header.h
class Employee : public Library
{
private:
pthread_t my_thread;//thread declare
public:
Employee();
int issueBook();
};
main.cpp
class threadClass
{
public:
void *worker_thread(void *arg)
{
char *curtime;
char *bk_time = (char *)arg;
time_t now = time(0);
curtime = ctime(&now);
pthread_exit(NULL);
}
};
int main()
{
Employee emp ;
emp.issueBook(); //calling function
}
和function.cpp
int Employee :: issueBook()
{
int ret =0;
ret = pthread_create(&my_thread, NULL, &worker_thread,(void *)temp->book_time);//thread calling with a function name and argument
}
如何从function.cpp
文件调用main.cpp
文件中定义的线程函数?我可以调用threadClass
类的使用对象吗?我能在function.cpp
文件中得到这个threadClass
对象吗
你的代码的问题是pthread_create需要一个函数指针作为线程入口点,而你提供了&worker_thread,它不是一个函数,而是threadClass的成员函数。
你有两个选择:
- 去掉threadClass把worker_thread变成一个函数
- 声明worker_thread的状态,并将&threadClass::worker_thread传递给pthread_create
相关文章:
- 为什么我不能在主函数之外定义一个类的对象(它继承了另一个类)?
- 如何在 c++ 中定义一个将被另一个短语替换的短语?
- 在销毁期间从另一个线程调用对象上调用方法是否未定义行为?
- 使用命名空间在另一个".cpp"文件中定义
- C++ 在一个源文件中使用另一个源文件中的矢量定义
- 为什么通过定义另一个指针单元格,整个代码停止工作?
- C++:为什么允许在另一个函数中声明函数,而不允许在函数定义中声明?
- 如何在一个函数中定义一个变量,并在另一个函数中访问和更改它?(C++)
- 访问从联合与另一个成员集复制的联合中的一个成员是否未定义或未指定?
- 是否可以使用另一个lua文件中定义的表,该表在当前文件中不需要作为模块
- 在另一个文件中初始化的 extern 数组中未定义的引用
- C++:如何从另一个谓词定义泛型而不是谓词
- 为什么相同的函数签名只有区别,另一个通过 const 获取参数是重新定义?
- 根据是否定义了另一个宏来评估宏
- 如何提前终止在另一个文件中定义的函数?
- 在另一个文件中定义函数后,Visual Studio 无法识别该函数
- 如何在另一个类模板中定义完全专用类的构造函数
- GLM如何在不声明内联函数并在另一个(未连接的?)文件中将其定义的函数逃脱
- 是否可以定义另一个预处理器指令
- 如何定义另一个模板类的内部模板类的构造函数