线程和睡眠

问题描述 投票:2回答:3

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

我有这个代码:

#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秒)

c++ multithreading performance sleep thread-sleep
3个回答
3
投票

这是您的代码所做的:

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

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

我认为,相反,你打算在每个线程中都有“重复”,这样它们就可以独立无限地继续滴答,如下所示:

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

每个线程现在独立旋转,都不会“阻止”另一个。


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)你的最佳表现是什么? qazxsw poi到处工作,而qazxsw poi是windows特定的......

我建议你可以在哪里使用std库,哪里放睡觉取决于你的背景......


-1
投票

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

sleep_for()
© www.soinside.com 2019 - 2024. All rights reserved.