多线程与互斥锁的一个有关问题
多线程与互斥锁的一个问题
为何这样counter达不到10K?
lock()不是会一直堵塞吗?
但是如果把(1)cout 那句注释去掉, 经过一段时间的输出字符串等待, counter每次就都会到达10k.
------解决方案--------------------
好高级的C++。。。你的mutex是不是每个线程都创建一个了?mutex放到全局,这样才起作用啊
void attempt_10k_increaces(int& counter)
{
std::mutex mtx;
for (int i=0; i<10000; ++i)
{
mtx.lock();
++counter;
//std::cout << "In " << i << " C is " << counter << ", "; // (1)
mtx.unlock();
}
}
int main()
{
int counter = 0;
std::thread threads[10];
for (int i=0; i<10; ++i)
{
threads[i] = std::thread(attempt_10k_increaces, std::ref(counter));
}
for (auto& th : threads)
{
th.join();
}
std::cout << "Final value of counter is : " << counter << std::endl;
system("pause");
return 1;
}
为何这样counter达不到10K?
lock()不是会一直堵塞吗?
但是如果把(1)cout 那句注释去掉, 经过一段时间的输出字符串等待, counter每次就都会到达10k.
------解决方案--------------------
好高级的C++。。。你的mutex是不是每个线程都创建一个了?mutex放到全局,这样才起作用啊