c++ 11线程在linux和windows上的不同行为

c++ 11 Threads different behaviour on linux and windows

本文关键字:windows 线程 linux c++      更新时间:2023-10-16
#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_functionn";
    }
}
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

但是在linux上使用gcc的输出是不同的

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上同步?

mutex只是一个锁,用于防止对共享资源的并发访问,在本例中为std::cout。在这两种情况下,一次只有一个线程写入std::cout。虽然在某些情况下解锁互斥锁可能会导致唤醒另一个任务,但这不是您应该期望或依赖的事情,除非您自己负责操作系统/调度器代码。

互斥锁限制访问std::cout:如果你在没有锁保护的情况下运行相同的代码,你可能会在一个操作系统或另一个操作系统上看到乱码/混合输出。

事实上,你在Visual Studio中看到类似的事情纯粹是巧合,并不能保证,事实上,你在Linux下看到的其他事情更可能是IO执行方式的差异,而不是线程操作方式的差异。

我猜测你在这里实际想做什么,但我怀疑你想要一个condition_variable和notify_one。但是,您不应该再假设它会循环。

同样,joinable()测试线程是否正在运行,join()等待它们停止,但是由于您的线程处于永久循环中,对join()的第一次调用将永远挂起。

—EDIT—

当我在Visual Studio 2015下使用/O2运行代码时,我得到与Linux报告相同的输出。