1. 没有mutex
#include#include #include int globalVariable = 0; void task1() { for(int i = 0; i < 1000000; i++) { globalVariable++; globalVariable--; } } int main(int argc, const char * argv[]) { std::thread t1(task1); std::thread t2(task1); t1.join(); t2.join(); std::cout<<"current value is "< xcode, command+r 运行结果为1,本来++和-- ,最后结果为0才对的,但是最后结果为1。
current value is 1
Program ended with exit code: 02. 加上mutex
#include#include #include std::mutex mtx; int globalVariable = 0; void task1() { for(int i = 0; i < 1000000; i++) { mtx.lock(); globalVariable++; globalVariable--; mtx.unlock(); } } int main(int argc, const char * argv[]) { std::thread t1(task1); std::thread t2(task1); t1.join(); t2.join(); std::cout<<"current value is "< xcode, command+r 运行结果为0, 正确。
current value is 1
锁之间的代码叫做临界区



