简体   繁体   English

在课程中创建新线程(Windows)

[英]Create new thread in class (windows)

I want to create a new thread in a class. 我想在一个类中创建一个新线程。 The problem is when I need to pass a pointer to the function that will be used in the new thread. 问题是当我需要将指针传递给将在新线程中使用的函数时。 I am unable to pass a pointer to the function. 我无法将指针传递给该函数。 A class function under the hood is basically this right? 底层的类功能基本上是这样吗?

void foo (this);

Then why does this code refuse to compile? 那为什么这个代码拒绝编译呢?

class TimeClass
{
private:
    DWORD   dwThreadId;
    HANDLE  hThread;

    LPTHREAD_START_ROUTINE Timer ();
public:
    TimeClass ();
};

TimeClass::TimeClass ()
{
    dwThreadId = CreateThread (NULL, 0, Timer, this, 0, &dwThreadId);
}

The signature of a thread function must be 线程函数的签名必须是

DWORD WINAPI ThreadProc(LPVOID param);

An ordinary (ie nonstatic) C++ member function does not have the WINAPI calling convention so it cannot be used as a thread function. 普通(即,非静态)C ++成员函数没有WINAPI调用约定,因此不能用作线程函数。 If you declare the member function as static then it can be used as a thread function: 如果将成员函数声明为静态,则可以将其用作线程函数:

static DWORD WINAPI ThreadProc(LPVOID param);

A class function under the hood is basically this right? 底层的类功能基本上是这样吗?

void foo (this); 无效foo(this);

Generally, no. 通常,不会。 It is what the compiler decides it to be, and there may be all kinds of 'non-virtual thunks', inlines, etc. The compiler is allowed to optimize the program in any way that doesn't change the program's behaviour, and such implementation details are not defined by the standard. 这就是编译器决定的样子,并且可能存在各种“非虚拟重击”,内联等等。允许编译器以不改变程序行为的任何方式来优化程序。实施细节未由标准定义。 That's why what you're trying to do is UB, and your best bet here (IMHO) would be something like: 这就是为什么您想要做的是UB,而您最好的选择(IMHO)如下:

extern "C" wrapper(void * p)
{
    static_cast<TimeClass*>(p)->whatever();
}

The ThreadProc() prototype is ThreadProc()原型是

DWORD WINAPI ThreadProc(
  _In_  LPVOID lpParameter
);

So you need to change the Timer() declaration like: 因此,您需要像下面这样更改Timer()声明:

DWORD WINAPI Timer()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM