c++ - 在 C++ 中传递函数指针

标签 c++ windows multithreading function pointers

我想完成这段简单的代码工作。

#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/

相关文章:

c++ - 我的简单线程安全堆栈有什么问题?

C++ 在所有其他类中使用(通信)对象

c++ - 套接字连接从分离的线程中止

windows - 拥有一个装满旧东西的注册表会减慢 Windows 的速度吗?

c++ - c++ - 如何让客户端在将数据写入管道之前检查服务器是否完成了从管道的读取操作

windows - Windows 上的 ubuntu 上的 bash 上的外部硬盘驱动器

c# - 信号量停止我的线程

c++ - std::condition_variable在阻塞之前是否真的解锁了给定的unique_lock对象?

c++ - Asio 点对点网络编程

c++ - 这是 unique_ptr 的正确用法吗?