【问题标题】:Thread on WindowsWindows 上的线程
【发布时间】:2011-12-05 15:39:42
【问题描述】:

我有一个关于 Windows 线程的小问题。我有以下代码:

main.cpp

int     main(int ac, char **av)
{
  std::vector<Mthread *>    mythread;
  std::list<std::string>    stack;
  DWORD     id = 0;

  stack.push_back("Maison");
  stack.push_back("Femmes");
  stack.push_back("Fetes");
  stack.push_back("Voitures");
  stack.push_back("Nounours");
  while (id != 5)
  {
      mythread.push_back(new Mthread());
      mythread[mythread.size() - 1]->initThread(&stack, id);
      id++;
  }
  id = 0;
  while (id != 5)
  {
      WaitForInputIdle(mythread[id]->getThread(), INFINITE);
      id++;
  }
  return (1);
}

和正在创建我的Mthread 类的 Mthread.cpp。

Mthread::Mthread() {}

Mthread::~Mthread() {}

HANDLE      Mthread::getThread(void) const
{
    return (this->thread);
}

bool        Mthread::initThread(std::list<std::string> *list, DWORD ID)
{
    this->save = list;
    this->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Mthread::ThreadFunc, (LPVOID)list, 0, &ID);
    if (this->thread == NULL)
    {
        std::cout << "Erreur lors du lancement du thread" << std::endl;
        return (false);
    }
    else
    {
        return (true);
    }
}

void        Mthread::ThreadFunc(LPVOID list)
{
        std::cout << " is launch" << std::endl;
}

代码可以运行,但我有一个小问题:终端上没有写入任何字符串。 但是,如果我将代码更改为:

bool        Mthread::initThread(std::list<std::string> *list, DWORD ID)
{
    this->save = list;
    this->thread = CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)Mthread::ThreadFunc, (LPVOID)list, 0, &ID);
    if (this->thread == NULL)
    {
        std::cout << "Erreur lors du lancement du thread" << std::endl;
        return (false);
    }
    else
    {
        std::cout << "OK" << std::endl;
        return (true);
    }
}

好吧,“OK”和“is launch”在终端上写了 5 次。我不明白为什么。 当我将一个小字符串 a 传递给 cout 时,它似乎正在工作,但是当我没有写任何东西时。

【问题讨论】:

  • 您预计会发生什么?你的 std::list/stack 的目的是什么?您所说的“关于 cout 的小文字”是什么意思?
  • 好吧,在我添加Sleep(4); 之后,只有一个is launch 正在写入而不是5。你知道一个函数正在等待线程的结束执行吗?

标签: c++ windows multithreading process


【解决方案1】:

简短的回答:我猜你的 main() 在线程有机会运行之前就终止了。添加一个 sleep() 或类似于 main 的东西。

更复杂的答案: - 线程和主线程彼此独立运行。您必须在 main 中等待,直到您知道可以退出 main。 - 您的程序往往是不安全的,因为所有线程都在没有任何同步的情况下访问该向量。阅读锁、互斥锁和信号量!

【讨论】:

  • 是的,我知道向量。在我解决我的问题后我会锁定它,因为我需要使用它。我更新我的问题。我在我的主要添加WaitForInputIdle。但它总是不起作用......
  • 不要使用WaitForInputIdle。有关要使用的正确函数族,请参阅 Shawnone 的答案。
【解决方案2】:

在终止之前,您的程序应该等到线程完成它们的工作。在 Windows 上,查看WaitForMultipleObjects

【讨论】:

    猜你喜欢
    • 2011-03-09
    • 1970-01-01
    • 2019-09-09
    • 1970-01-01
    • 1970-01-01
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多