【发布时间】:2015-07-04 03:40:27
【问题描述】:
我是 C++11 多线程的初学者。我正在使用小代码并遇到了这个问题。代码如下:
#include <iostream>
#include <thread>
#include <vector>
#include <mutex>
std::mutex print_mutex;
void function1()
{
std::cout << "Thread1 started" << std::endl;
while (true)
{
std::unique_lock<std::mutex> lock(print_mutex);
for (size_t i = 0; i<= 1000000000; i++)
continue;
std::cout << "This is function1" << std::endl;
lock.unlock();
}
}
void function2()
{
std::cout << "Thread2 started" << std::endl;
while (true)
{
std::unique_lock<std::mutex> lock(print_mutex);
for (size_t i = 0; i <= 1000000000; i++)
continue;
std::cout << "This is function2" << std::endl;
lock.unlock();
}
}
int main()
{
std::thread t1(function1);
std::thread t2(function2);
t1.join();
t2.join();
return 0;
}
我已经编写了代码,直觉期待以下输出:
Thread1 已启动
Thread2 已启动
这是 function1
这是 function2
这是 function1
。 .
.
.
但是显示的输出如下:
线程 1 已启动
线程 2 已启动这是函数1
这是函数1
这是 函数1
.
.
.
我哪里错了?
【问题讨论】:
-
您使用的是哪个编译器?使用 Visual Studio 2013,结果符合预期。
-
嗯,我认为无法预测这些线程的调度方式,因此我认为第一个输出是完全有效的。您应该在解锁后将其放在循环中以获得所需的输出,但即使那样我认为您也无法保证您将始终获得相同的输出。
-
我在 ubuntu 14.10 上使用 g++ 4.9.1。
-
有点离题,但值得一提的是,这两个
lock.unlock()语句是无害的,但完全没有必要。使用std::unique_lock的全部意义在于,当它超出范围时,它将自动解锁其关联的互斥锁。此外,这两个延迟循环可能会被优化掉。你最好使用std::this_thread::sleep_for()之类的东西。 -
Ferruccio,这对初学者来说是一个很好的优化技巧。是不是当持有锁的线程进入休眠状态时,锁会切换到其他等待线程..??
标签: c++ multithreading c++11 thread-synchronization