在另一个类中创建线程

Creating a thread in another class

本文关键字:创建 线程 另一个      更新时间:2023-10-16

我试图在ThreadMe类中为名为thefunction()的函数在主函数中创建一个线程。棘手的部分是,我需要启动一个线程在另一个类TYIA -Roland

#include <iostream>
#include <process.h>
#include <windows.h>
int main()  {
    char cincatcher[24];
        std::cout << "I want to run a thread using a function on another classn";
//      Here is a good place to start the thread
        while( true )   {

        std::cin >> cincatcher
    }
}

class ThreadMe  {
    void thefunction();
};
void ThreadMe::thefunction()    {
    while( true )   {
        std::cout << "working!n"
        Sleep(800);
    }
}

不能用类方法直接启动线程。您必须将类方法包装到一个普通函数中,然后使用该函数启动线程。例如:

void threadBody(void *p) {
     ThreadME tm;
     tm.thefunction();
}