当我运行这段代码时:
#include <iostream>
#include <thread>
#include <mutex>
std::mutex m;
int main()
{
std::vector<std::thread> workers;
for (int i = 0; i < 10; ++i)
{
workers.emplace_back([i]
{
std::lock_guard<std::mutex> lock(m);
std::cout << "Hi from thread " << i << std::endl;
});
}
std::for_each(workers.begin(), workers.end(), [] (std::thread& t)
{ t.join(); });
}
我得到了output http://melpon.org/wandbox/permlink/fCN7yigWoprULRPS:
Hi from thread 7
Hi from thread 1
Hi from thread 4
Hi from thread 6
Hi from thread 0
Hi from thread 5
Hi from thread 2
Hi from thread 3
Hi from thread 9
Hi from thread 8
尽管我使用互斥体一次只保留一个线程访问。为什么输出不按顺序?
您的互斥体实现的是没有两个线程同时打印。然而,他们仍在争夺哪个线程首先获取互斥体。
如果你想串行执行,你可以完全避免线程。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)