c++ 11线程在linux和windows上的不同行为
c++ 11 Threads different behaviour on linux and windows
#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报告相同的输出。
相关文章:
- 自 Windows 10 20H1 以来,具有单独线程的多个窗口停止工作
- 互斥,Windows 10,c ++,在一个线程上获取,在另一个线程上发布
- 多线程Windows GUI应用程序中的死锁
- 用于线程间通信的 Windows 套接字
- 如何使用 Ryzen 7 修复 Windows 上 Qt 5.9 线程的处理器关联
- 睡眠:(睡眠或usleep)并没有将我的线程中的所有内容悬挂在Linux中,而是在Windows中悬挂吗?为什么
- 另一个应用程序用 c++ 在 Windows 上的线程中破坏 QTimer
- Windows 线程池,'PTP_CALLBACK_INSTANCE':未声明的标识符
- 如何将向量返回到 Windows 线程函数
- 从 std::thread::id 结构中检索 Windows 线程标识符
- Windows 线程:并行合并排序
- 如何在Windows线程中终止线程后获取剩余线程数?C++
- 将 Windows 线程中编写的代码转换为 wxwidgets 线程
- c++作用域和Windows线程
- 确定Windows线程是否处于临界区或类似的位置
- Win32 windows线程安全吗?
- 如何让Windows线程池调用类成员函数
- 连接和终止windows线程
- Windows线程从另一个线程休眠和唤醒
- Windows线程创建过程中的内存管理