线程和睡眠

thread and 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)); 并且在下一个循环中不显示 std::thread t1(function1); 的下一个 Hi I'm the function 1,直到睡眠线程结束。

1) 你知道为什么吗?

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

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 是 windows 特定的....

我建议尽可能使用 std 库,在哪里放置睡眠取决于您的上下文...

这就是您的代码所做的:

  • 启动线程 1
    • 输出一条消息
    • 等待 1 秒
    • 输出另一条消息
  • 启动线程 2
    • 输出一条消息
    • 等待 5 秒
    • 输出另一条消息
  • 等待两个线程完成
    • (这大约需要 5 秒)
  • 无限期重复

您已声明这不是您的本意。

我认为,相反,您打算让每个线程的 "repeat" 内部 ,以便它们继续独立且无限期地滴答作响,如下所示:

#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 秒
    • 输出另一条消息
    • 无限期重复
  • 等待两个线程完成
    • (虽然永远不会!)

现在每个线程都独立旋转,"block" 另一个也不会。

当您加入一个线程时,它会完成执行并退出。因此,当您加入线程时 t1.join();和 t2.join();,第二个语句将仅在第一个连接语句完成时执行。因此,在您的情况下,要连续增加线程并并行执行,您必须像下面这样分离线程:-

int i = 0;
while(true) {

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

 t1.detach();
 t2.detach();

//also break your infinite loop here
if( ++i < 4)
   break;
}