class MyThread : public FRunnable
{
private:
MyThread(uint8 *pixcel);
~MyThread();
virtual uint32 Run() override;
virtual void Stop() override;
private:
FRunnableThread *runnableThread = nullptr;
static MyThread *m_pInstance;
bool m_bRun;
uint8 *m_pixcel;
public:
static MyThread *instance(uint8 *pixcel)
{
if (NULL == m_pInstance)
{
m_pInstance = new MyThread(pixcel);
}
return m_pInstance;
};
static void destroy()
{
if (m_pInstance)
{
delete m_pInstance;
m_pInstance = NULL;
}
};
};
MyThread* MyThread::m_pInstance = nullptr;
MyThread::MyThread(uint8 *pixcel)
{
m_pixcel = pixcel; //外部传入的内存指针,可以没有
runnableThread = FRunnableThread::Create(this, TEXT("MyThread"), 0);
m_bRun = true;
}
MyThread::~MyThread()
{
m_bRun = false;
delete runnableThread;
runnableThread = NULL;
}
uint32 MyThread::Run()
{
while (m_bRun)
{
//逻辑处理代码
int k = 0;
for (int i = 0; i < 1024; i++)
{
for (int j = 0; j < 1024; j++)
{
m_pixcel[k++] = Random(0, 255); //b
m_pixcel[k++] = Random(0, 255); //g
m_pixcel[k++] = Random(0, 255); //r
m_pixcel[k++] = 255;
}
}
FPlatformProcess::Sleep(0.01f);
}
return 0;
}
void MyThread::Stop()
{
m_bRun = false;
if (runnableThread != NULL)
runnableThread->WaitForCompletion();
}
1. 在C++中,actor的BeginPlay()和EndPlay()都会被执行多次,在运行程序的时候,BeginPlay()会执行两次,关闭程序的时候,
EndPlay()会执行三次,因此,线程的创建和销毁不能简单在BeginPlay()和EndPlay()里做。而是需要把线程类做成单例。
在BeginPlay()里面调用单例类的instance来创建,在EndPlay()里面调用单例类的destroy来销毁。
比如,在BeginPlay里面,m_myThread = MyThread::instance(pMemMFCD);
在EndPlay()里面,MyThread::destroy();
2. FRunnable的Stop虚函数如果被复写的话,他是在delete FRunnableThread的时候自动调用的。
3. FRunnable的Run函数复写,将自己的逻辑代码放入其中,调用FRunnableThread的Create后,Run会自动运行。
4. 最好增加一个线程停止运行的标志位,在销毁线程前,先把这个标准位置为false,让线程自己停止运行,然后调用
FRunnableThread的WaitForCompletion等待线程结束后,再做后续的清理工作。