在多线程中经常会遇到多个线程同时修改同一个变量的情况,这个时候如果不对线程进行一定约束,很可能会导致意想不到的结果。例如有两个线程1和线程2,线程2的输入是线程1的结果。很显然如果在主线程中同时开启了线程1和线程2,它们是同时运行的,会直接导致程序的崩溃。所以线程同步锁应运而生,当遇到它时它会让当前线程独占某个变量,其它同样需要修改该变量的线程此时只能处于等待状态,等到当前线程结束之后,线程独占锁自动释放,其它线程可以修改内容。
// mutex example
#include <iostream> // std::cout
#include <thread> // std::thread
#include <mutex> // std::mutex
std::mutex mtx; // mutex for critical section
int counter=0;
void print_block (int n) {
// critical section (exclusive access to std::cout signaled by locking mtx):
// mtx.lock();
for (int i=0; i<n; ++i) {
// std::cout << '\n';
std::this_thread::sleep_for(std::chrono::milliseconds(1));
counter++;}
// mtx.unlock();
}
int main ()
{
std::thread th1 (print_block,50);
std::thread th2 (print_block,50);
th1.join();
th2.join();
std::cout << "counter:" << counter << std::endl;
return 0;
}
#include<thread>
#include<mutex>
using namespace std;
const int N = 100000000;
int num(0);
mutex m;
void run()
{
for (int i = 0; i < N; i++)
{
m.lock();
num++;
m.unlock();
}
}
int main()
{
clock_t start = clock();
thread t1(run);
thread t2(run);
t1.join();
t2.join();
clock_t end = clock();
cout << "num=" << num << ",用时 " << end - start << " ms" << endl;
return 0;
}
运行结果:
num=200000000,用时 128323 ms
加锁后计算正确,但由于加锁和解锁导致时间增加;