我试图将一个私有成员函数(不应该是公共的或受保护的)作为具有Win32函数QueueUserWorkItem()
的工作项调用。我知道我以前做过这件事很容易,但是现在我找不到那个片段了,我也无法让bind()
伏都教工作。因此,对于这个问题,课程是:
class Arbitrary {
public:
Arbitrary() ;
~Arbitrary() ;
bool UsefulPublicFunction(unsigned uParameter) ;
protected:
private:
void PrivateWorkItem(void* pVoid) ;
} ;
在UsefulPublicFunction()
内,我们可能会看到:
LPTHREAD_START_ROUTINE pThreadStartRoutine ;
ULONG uFlags = 0 ;
void* pContext = nullptr ;
if (QueueUserWorkItem(pThreadStartRoutine, pContext, uFlags)) {
//blah blah blah
}
我似乎在杂草中出现的是pThreadStartRoutine
的作业,例如:
pThreadStartRoutine = std::bind<&Arbitrary::PrivateWorkItem, this, std::placeholders::_1> ;
我认识到PrivateWorkItem
的签名可能会改为:
private:
DWORD WINAPI PrivateWorkItem(void* pVoid) ;
即使有了这种改变,也没有快乐。 VS2015真的很讨厌我使用bind()
的方式。
我对pThreadStartRoutine
的任务应该是什么样的?
答案 0 :(得分:2)
这似乎有效:
#include <Windows.h>
#include <stdio.h>
#include <functional>
using namespace std::placeholders;
class Arbitrary {
public:
bool UsefulPublicFunction(int uParameter);
protected:
private:
typedef std::function<void (void)> CallbackType;
static DWORD WINAPI ProcessWorkItem(void* pVoid);
void PrivateWorkItem1(int arg1, int arg2);
void PrivateWorkItem2(char * arg1);
};
void Arbitrary::PrivateWorkItem1(int arg1, int arg2)
{
printf("Numbers are %u %u\n", arg1, arg2);
return;
}
void Arbitrary::PrivateWorkItem2(char * arg1)
{
printf("String is %s\n", arg1);
return;
}
DWORD WINAPI Arbitrary::ProcessWorkItem(void* pVoid)
{
CallbackType * callback = static_cast<CallbackType *>(pVoid);
(*callback)();
delete callback;
return 0;
}
bool Arbitrary::UsefulPublicFunction(int param1)
{
QueueUserWorkItem(&ProcessWorkItem, new CallbackType(std::bind(&Arbitrary::PrivateWorkItem1, this, param1, 7)), 0);
QueueUserWorkItem(&ProcessWorkItem, new CallbackType(std::bind(&Arbitrary::PrivateWorkItem2, this, (char *)"This is my string")), 0);
Sleep(1000);
return true;
}
int main(int argc, char ** argv)
{
Arbitrary x;
x.UsefulPublicFunction(5);
return 0;
}
答案 1 :(得分:1)
尝试更像这样的东西:
class Arbitrary {
public:
Arbitrary() ;
~Arbitrary() ;
bool UsefulPublicFunction(unsigned uParameter);
protected:
private:
static DWORD WINAPI PrivateWorkItem(void* pVoid) ;
void PrivateFunction();
} ;
DWORD WINAPI Arbitrary::PrivateWorkItem(void* pVoid)
{
static_cast<Arbitrary*>(pVoid)->PrivateFunction();
return 0;
}
...
if (QueueUserWorkItem(&PrivateWorkItem, this, 0)) {
//blah blah blah
}