线程过程为非静态 [英] Thread Procedure as non-static

查看:78
本文介绍了线程过程为非静态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



如何使线程过程访问非静态成员变量?朴素的举个例子..

谢谢,
Laje ...

Hi,

How to make a thread procedure to access non-static member variables? Plaese give me a detial example..

Thanks,
Laje...

推荐答案

1创建线程的参数是用户数据.将您的类实例作为用户数据传递.
我发现最简单的方法是,如果我需要多次访问变量,则可以从静态函数中调用非静态函数.

1 of the parameters to creating the thread is User Data. Pass in your class instance as the User Data.
I find that the easiest way is to call a non-static function from the static function if I need to access variables more than a few times.

//Create the thread
m_hThread = CreateThread(NULL, 0, &ThreadProc, this, 0, NULL);

//The static member function for the callback
DWORD WINAPI MyClass::ThreadProc(void *pInst) {
	return ((MyClass *)pInst)->ThreadProcInternal();
}

//Non-static member function to use as normal
DWORD MyClass::ThreadProcInternal() {
	m_nMyNumber = 0; //for eg.
}




此示例使用Win32线程,但是对于所有线程实现(例如pthread),其原理都是相同的.它们都带有用户定义的参数.




This example uses Win32 Threads, but the principal is the same for all thread implementations like pthreads. They all take a user defined parameter.


这篇关于线程过程为非静态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆