1. 例子
1. 不加 互斥锁
#include <iostream>
#include <thread>
#include <mutex>
volatile int nunber(0);
std::mutex mtx;
void thrfunc() {
for (int i = 0; i < 1000000; i++) {
// mtx.lock();
++counter;
//mtx.unlock();
}
}
int main(int argc, const char* argv[]) {
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(thrfunc);
for (auto& th : threads)
th.join();
std::cout << "count to " << counter << " Succeddfully." << std::endl;
return 0;
}
1. 结果(在 VS 2019
不是 1,000,000
):
2. 结果报错 (g++ 4.7
)
terminate called after throwing an instance of 'std::system_error'
what(): Enable multithreading to use std::thread: Operation not permitted
Aborted
2. 加上 互斥锁
#include <iostream>
#include <thread>
#include <mutex>
volatile int number(0);
std::mutex mtx;
void testfunc() {
for (int i = 0; i < 1000000; i++) {
mtx.lock();
++number;
mtx.unlock();
}
}
int main(int argc, const char* argv[]) {
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(testfunc);
for (auto& th : threads)
th.join();
std::cout << "count to " << number << " Succeddfully." << std::endl;
return 0;
}
- 结果就是我们想要的结果:
2. 原因
典型的 生产者-消费者
模型(此处 进程
和 线程
的原理是一样的)
-
根源:因为
counter++
不是原子操作
-
解决办法:(
上锁
)
#include <iostream>
#include <thread>
#include <mutex>
volatile int number(0);
std::mutex mtx;
void testfunc() {
for (int i = 0; i < 1000000; i++) {
mtx.lock(); // 上锁
++number;
mtx.unlock(); // 开锁
}
}
int main(int argc, const char* argv[]) {
std::thread threads[10];
for (int i = 0; i < 10; ++i)
threads[i] = std::thread(testfunc);
for (auto& th : threads)
th.join();
std::cout << "count to " << number << " Succeddfully." << std::endl;
return 0;
}