【发布时间】:2015-05-25 09:07:59
【问题描述】:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex mx;
void some_function()
{
while(1)
{
std::lock_guard<std::mutex> mx_guard(mx);
std::cout << "some_function()\n";
}
}
void some_other_function()
{
while(1)
{
std::lock_guard<std::mutex> mx_guard(mx);
std::cout << "some_other_function\n";
}
}
int main()
{
std::thread t1(some_function);
std::thread t2 = std::move(t1); //t2 will be joined
t1 = std::thread(some_other_function);
if(t2.joinable())
{
std::cout << "t2 is joinable()\n";
t2.join(); //calling join for t1
}
if(t1.joinable())
{
std::cout << "t1 is joinable()\n";
t1.join();
}
return 0;
}
我在 windows 和 linux 上对该程序有不同的输出。在使用 Visual Studio 13 编译器的 Windows 上,我得到以下输出。
some_function()
some_other_function
some_function()
some_other_function
some_function()
some_other_function
some_function()
some_other_function
some_function()
some_other_function
some_function()
some_other_function
但是在使用 gcc 的 linux 上输出是不同的
some_function()
some_function()
some_function()
some_function()
some_function()
some_function()
some_function()
some_other_function
some_other_function
some_other_function
some_other_function
some_other_function
some_other_function
some_other_function
在 windows 上,两个线程一个接一个地打印,但在 linux 上,它的行为不一样。在 linux 上使用互斥锁不同步。如何在linux上同步?
【问题讨论】:
-
您的系统有多少个 CPU?不保证线程之间的执行顺序。
-
“在 linux 上使用互斥锁不同步” - 您无法从该输出中得出结论。完全没有。
-
你究竟打算做什么?如果您提供的只是样板文件,我们将无法帮助您。
-
std::cout << "some_function()\n";您在输出后缺少cout.flush(),这可能很好地解释了不同的行为。 -
你想同步什么?目前,您正在同步对 std::cout 的访问,仅此而已。您的互斥锁只是保证您不会得到如下输出:“some_funsome_other_function\nction()\n”
标签: c++ linux windows multithreading c++11