#include "iostream"
#include "thread"
#include "mutex"

using namespace std;

int num=0;

mutex m;

/**
 * 线程不安全
 */
void run(){

    clock_t start = clock();
    for(int i=0;i<1200000;i++) {
        num++;
    }
    clock_t end = clock();
    cout << "id=" << this_thread::get_id << ",num="<< num << endl;
    cout << "spent time" << (end-start)/CLOCKS_PER_SEC << "s" << endl;
}


/**
 * 线程安全
 */
void mutexrun(){
    clock_t start = clock();
    for(int i=0;i<1200000;i++) {
//        cout << "i=" << i << endl;
        m.lock();
        num++;
//        cout << "num=" << num << endl;
        m.unlock();
    }
    clock_t end = clock();
    cout << "id=" << this_thread::get_id << ",num="<< num << endl;
    cout << "spent time" << (end-start)/CLOCKS_PER_SEC << "s" << endl;
}

int main(){
//    thread t1 (run);
//    thread t2 (run);

    thread t1 (mutexrun);
    thread t2 (mutexrun);

    cin.get();
}