线程和睡眠

时间:2018-03-01 16:34:40

标签: c++ multithreading performance sleep thread-sleep

我试图了解多线程的工作原理。

我有这段代码:

#include <iostream>
#include <thread>
#include <chrono>

void function1() {

   std::cout << "Hi I'm the function 1" << std::endl;
   std::this_thread::sleep_for(std::chrono::seconds(1));
   std::cout << "Hi I'm the function 1 after sleeping" << std::endl;

}

void function2() {

  std::cout << "Hi I'm the function 2" << std::endl;
  std::this_thread::sleep_for(std::chrono::seconds(5));
  std::cout << "Hi I'm the function 2 after sleeping" << std::endl;

}

int main()
{

  while(true) {

     std::thread t1(function1);
     std::thread t2(function2);

     t1.join();
     t2.join();

  }

  system("pause");
  return 0;

}

问题是当我运行它时,它停止等待std::this_thread::sleep_for(std::chrono::seconds(5));并且在下一个循环中不显示Hi I'm the function 1的下一个std::thread t1(function1);,直到睡眠线程结束。

1)你知道为什么吗?

2)我希望主要继续循环并且不要等到t2完成(从function2的sleep_for()设置为5秒)

3 个答案:

答案 0 :(得分:3)

这就是您的代码所做的事情:

  • 启动主题1
    • 输出讯息
    • 等待1秒
    • 输出另一条消息
  • 启动主题2
    • 输出讯息
    • 等待5秒
    • 输出另一条消息
  • 等待两个线程完成
    • (这将花费大约5秒钟)
  • 无限期重复

你已经声明这不是你想做的事。

我认为,相反,你打算让#34;重复&#34;每个线程的内部,以便它们可以独立无限地继续滴答,如下所示:

#include <iostream>
#include <thread>
#include <chrono>

void function1() {
   while (true) {
      std::cout << "Hi I'm the function 1" << std::endl;
      std::this_thread::sleep_for(std::chrono::seconds(1));
      std::cout << "Hi I'm the function 1 after sleeping" << std::endl;
   }
}

void function2() {
  while (true) {
     std::cout << "Hi I'm the function 2" << std::endl;
     std::this_thread::sleep_for(std::chrono::seconds(5));
     std::cout << "Hi I'm the function 2 after sleeping" << std::endl;
   }
}

int main()
{
   std::thread t1(function1);
   std::thread t2(function2);

   t1.join();
   t2.join();
}

现在您的代码执行此操作:

  • 启动主题1
    • 输出讯息
    • 等待1秒
    • 输出另一条消息
    • 无限期重复
  • 启动主题2
    • 输出讯息
    • 等待5秒
    • 输出另一条消息
    • 无限期重复
  • 等待两个线程完成
    • (虽然两者都不会!)

随着每个线程现在独立旋转,任何一个线程都不会&#34;阻止&#34;另一个。

答案 1 :(得分:0)

1)这是我的输出,似乎我的期望:

Hi I'm the function 1
Hi I'm the function 2
Hi I'm the function 1 after sleeping
Hi I'm the function 2 after sleeping
Hi I'm the function 1
Hi I'm the function 2
Hi I'm the function 1 after sleeping
Hi I'm the function 2 after sleeping
Hi I'm the function 2
Hi I'm the function 1
Hi I'm the function 1 after sleeping
Hi I'm the function 2 after sleeping
Hi I'm the function 2
Hi I'm the function 1
Hi I'm the function 1 after sleeping
Hi I'm the function 2 after sleeping
Hi I'm the function 2
Hi I'm the function 1

2)你的最佳表现意味着什么? sleep_for()适用于所有地方,而Sleep是特定于窗口的....

我建议你尽可能使用std库,睡觉取决于你的背景...

答案 2 :(得分:-1)

当你加入一个线程时,它将完成它的执行并退出。因此,当你加入你的线程t1.join();和t2.join();,第二个语句仅在第一个连接语句完成时执行。因此,在您的情况下,连续折叠线程并执行并行,您必须分离线程,如下所示: -

[Employee Number], [Absence Number], [Gap Date]
18615, 70, '16-Jan-2018'
18615, 70, '17-Jan-2018'
18615, 70, '25-Jan-2018'