我想完成这段简单的代码工作。
#include <iostream>
#include <windows.h>
void printSome (int i)
{
std::cout << i << std::endl;
}
void spawnThread (void (*threadName)(int i))
{
CreateThread
(
0, // default security attributes
0, // use default stack size
(LPTHREAD_START_ROUTINE)threadName, // thread function name
(LPVOID)i, // argument to thread function
0, // use default creation flags
0 // returns the thread identifier
);
}
int main ()
{
spawnThread(printSome(155));
}
我在 windows 上,使用 vs。任何帮助将不胜感激。
最佳答案
CreateThread 需要 2 个参数:指向作为线程执行的函数的指针,以及将提供给线程的 DWORD 参数。您的 spawnThread() 函数只有 1 个参数(threadName);你认为它有 2 个参数,因为“i”,但这实际上是“threadName”类型定义的一部分。 (您也可以省略“i”;也就是说,您不需要将参数命名为“threadName”。)
无论如何,鉴于您需要 2 个参数,请重新定义 spawnThread:
void spawnThread(void (*threadEntryPoint)(int), int argument)
{
CreateThread(0,0,
(LPTHREAD_START_ROUTINE)threadEntryPoint,
(LPVOID)argument,
0,0);
}
请注意,我没有命名 threadEntryPoint 的 int 参数;告诉编译器该函数必须有一个 int 参数就足够了。
并调用它:
spawnThread(printSome, 155);
无论如何,快速而肮脏,这会做你想做的事。
嗯。
赖利。
关于c++ - 在 C++ 中传递函数指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/402992/