如何调用在main中定义的另一个函数中的线程

How to call a thread inside another function and defined in main?

本文关键字:定义 另一个 线程 函数 main 何调用 调用      更新时间:2023-10-16

我正在编写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的成员函数。

你有两个选择:

  1. 去掉threadClass把worker_thread变成一个函数
  2. 声明worker_thread的状态,并将&threadClass::worker_thread传递给pthread_create
相关文章: