简体   繁体   English

如何在不使用C ++ 11线程的情况下使用functor作为线程函数在Windows中开始线程?

[英]How can I begin thread in windows using functor as thread function without using C++11 thread?

I'm writing a simple thread lib for Windows. 我正在为Windows编写一个简单的线程库。 I want to pass this functor 我想通过这个函子

struct callable
{
    void operator()()
    {
        for(int i = 0; ;++i)
        {
            std::cout << i << std::endl;
        }
    }
};

In _beginthread() this way: _beginthread()这种方式:

int main()
{  
    callable c;
    _beginthread(c, 0, 0);
}

but it's not possible. 但这是不可能的。 The ability to pass functor in the thread is very necessary for my library. 对于我的库,在线程中传递函子的功能非常必要。 I know that boost::thread provides this ability, thus it is possible. 我知道boost::thread提供了此功能,因此是可能的。 How can I begin thread in windows using functor as thread function without using C++11 thread? 如何在不使用C ++ 11线程的情况下使用functor作为线程函数在Windows中开始线程?

[upd] without using C++11 thread [upd]不使用C ++ 11线程

The standard technique is as follows: 标准技术如下:

  • Define a struct to hold whatever information you need to pass to the thread. 定义一个结构以保存需要传递给线程的任何信息。 In your case that information is the callable functor. 在您的情况下,信息就是可调用的函子。 So, you already have a suitable struct at hand. 因此,您已经有了合适的结构。
  • Allocate one of these structs on the heap. 在堆上分配这些结构之一。 This happens in the calling thread, but the information is passed to the created thread which is why it cannot live on the stack. 这在调用线程中发生,但是信息被传递到创建的线程,这就是为什么它不能存在于堆栈中的原因。
  • Call CreateThread passing a suitable thread proc (more later), and the address of your struct in the lpParameter parameter. 调用CreateThread并传递适当的线程proc(稍后再介绍),并在lpParameter参数中提供结构的地址。
  • In the thread proc, you are passed the address of the struct in lpParameter . 在proc线程中,将在lpParameter中传递该结构的地址。
  • Cast that pointer to the appropriate type and call your functor. 将该指针转换为适当的类型,然后调用函子。
  • Delete the heap allocated memory. 删除堆分配的内存。

The thread proc looks like this: 线程proc如下所示:

DWORD WINAPI ThreadProc(void *lpParameter)
{
    callable *c = (callable*)lpParameter;
    (*c)();
    delete c;
    return 0;
}

And the call to CreateThread is along these lines: CreateThread的调用遵循以下CreateThread行:

callable *c = new callable;
// initialise c
CreateThread(NULL, 0, ThreadProc, (void*)c, 0, &threadID);

I apologise if there are syntax errors here, I'm not at all fluent in C++. 我很抱歉如果这里有语法错误,我一点也不精通C ++。

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

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