c++ - LPTHREAD_START_ROUTINE/类数组

标签 c++ multithreading

我编写了一些像这样的测试代码,它编译并运行良好......

void threadtest()
{
  HANDLE hThrd;
  DWORD threadId;
  int i;

  for (i = 0;i < 5;i++)
  {
    hThrd = CreateThread(
      NULL,
      0,
      ThreadFunc,
      (LPVOID)i,
      0,
      &threadId );
  }
  // more stuff
}

DWORD WINAPI ThreadFunc(LPVOID n)
{
  // stuff
  return 0;
}

然后我想修改代码以将 ThreadFunc 放入一个类中,然后声明这些类的数组。我认为代码应该如下所示:

class thread_type
{

  public:

  DWORD WINAPI ThreadFunc(LPVOID n)
  {
    // stuff
    return 0;
  }
};

void threadtest()
{
  HANDLE hThrd;
  DWORD threadId;
  int i;
  thread_type *slave;

  slave = new thread_type[5];

  for (i = 0;i < 5;i++)
  {
    hThrd = CreateThread(
    NULL,
    0,
    slave[i].ThreadFunc,
    (LPVOID)i,
    0,
    &threadId );
  }
  // more stuff
}

不幸的是,编译器提示行slave[i].ThreadFunc,我想我可能需要一些特殊的转换,但我尝试的所有涉及“::”和“&”的排列似乎都失败了(我对C++)。真实的代码有一些额外的复杂性,为了清楚起见,我没有包括这些复杂性,但我认为它们是无关紧要的。

最佳答案

代码的第一个问题是测试类不是 thread_type 的后代。您需要以某种方式指定基类。 其次,如果您传递函数指针,则不应该是 thiscall 类型。解决方案通常是这样的:

struct thread
{
  virtual void
  run() = 0;

  static thread_func(void* param)
  {
    thread* pThread = (thread*)param;
    thread->run();
  }
}


struct worker : public thread
{
  void
  run()
  {
    (.. code for the thread...)
  }
}

void threadtest()
{
  HANDLE hThrd;
  DWORD threadId;
  int i;
  thread *slave;

  slave = new thread_type[5];
  slave[0] = new worker;
  slave[1] = new worker;
  slave[2] = new worker;
  slave[3] = new worker;
  slave[4] = new worker;

  for (i = 0;i < 5;i++)
  {
    hThrd = CreateThread(
    NULL,
    0,
    &thread::thread_func,
    (LPVOID)slave[i],
    0,
    &threadId );
  }
  // more stuff
}

请注意,这可能只是一个反射,我现在无法编译,因为我这里没有任何东西可以这样做,但逻辑应该是这样的。

关于c++ - LPTHREAD_START_ROUTINE/类数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1477239/

相关文章:

带有浮点参数的 C++ 模板

C++套接字设计

c# - 在 C# 中自动终止非必需线程

反转两个边界之间数组索引顺序的 C++ 递归函数

c++ - 断言在 VS2008 但不是在 VS2005

ruby-on-rails - Rails 创建新线程或后台进程

python - 使用 Kafka 在应用程序上打开太多文件错误

c# - 如何在 Xamarin.Forms 中制作平滑移动的音频 slider

java - 设置 Java 多线程亲和性

c++ - 模板函数错误: no operator found which takes a right hand operand of type