vmware 中的线程编程,'process scheduling' 没有发生

Thread programming in vmware, 'process scheduling' didn't happen

我正在虚拟机上学习一些线程编程。未按预期执行的代码如下:

#include <iostream>
#include <thread>
using namespace std;

void function01() {                                                                                                                   
      for (int i=0; i<100; i++) {                                                                                                   
               std::cout << "from t1:" << i << std::endl;                                                                            
      }                                                                                                                             
}   

int main() {
 // data race and mutex                                                                                                                                             
       std::thread t1( function01 );                                                                                                 
       for (int i=0; i<100; i++) {                                                                                                   
              std::cout << "from main:" << i << std::endl;                                                                          
       }                                                                                                                             
       t1.join();   
       return 0;
}

这些代码应该在标准输出上进行数据竞争。但是当我用

编译它时
:!g++ -std=c++11 -pthread ./foo.cpp

和运行,每次我得到一个结果,其中100次"t1"跟随100次"main"。令我困惑的是,当我在我的旧笔记本电脑上安装的另一个 ubuntu14.04 上做同样的事情时,代码按我的预期执行。这意味着此代码遇到了数据竞争。

我对vmware不是很了解。 vmware 上的线程 运行 是否被管理并且不会遇到数据竞争?

------------第二次编辑------------------------

谢谢大家。

core的数量可能是主要原因。将vm core的数量设置为多个后,我得到了预期的结果。

我认为问题出在 time slice。您可以通过在代码中引入一些延迟来自行验证。例如:

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

void function01() {
    for (int i=0; i<100; i++) {            
       std::cout << "from t1:" << i << std::endl;
       std::this_thread::sleep_for(std::chrono::duration<double, std::milli>{10});
    }
}   

int main() {
   // data race and mutex
   std::thread t1( function01 );
   for (int i=0; i<100; i++) {
       std::cout << "from main:" << i << std::endl;
       std::this_thread::sleep_for(std::chrono::duration<double, std::milli>{10});
   }

   t1.join();   
   return 0;
}

您的新机器可能比旧机器快得多。所以它能够在 main 进入它自己的循环之前完成 function01 的执行。

或者只有一个CPU,所以一次只能执行一个例程。而且因为你的循环需要的计算量非常小,所以 CPU 可以在 OS.

给它的一段时间内完成。

确保您的 VM 有多个 CPU 分配给它。并尝试使循环中的每个步骤 'heavier'.

double accumulator = 0;
for (int i=0; i<100; i++) {
    for (int j=1; j<1000*1000; j++)
        accumulator += std::rand();
    std::cout << "from t1:" << i << std::endl;
}