大挪耗

c++互斥锁

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

using namespace::std;



int aa=0;  //定义全局变量
mutex mtx;//创建互斥锁,保护共享资源aa变量。

//普通函数,把全局变量加1000000次。
void func()
{
    for (int ii = 0; ii < 1000000; ++ii) {
        cout<<"线程"<<this_thread::get_id()<<"申请加锁"<<endl;
        mtx.lock();
        cout<<"线程"<<this_thread::get_id()<<"加锁成功"<<endl;
        aa++;
        this_thread::sleep_for(chrono::seconds(2));
        mtx.unlock();
        cout<<"线程"<<this_thread::get_id()<<"释放了锁"<<endl;
        this_thread::sleep_for(chrono::seconds(1));
    }
}
void func1()
{
    for (int ii = 0; ii < 1000000; ++ii) {
        lock_guard<mutex> mlock(mtx);
        aa++;

    }
}
int main()
{
//    func();
//    func();
    //单线程输出2000000。
    //多线程输出1000000多一点。
    //用普通函数创建线程。
    thread t1(func1);//创建线程t1,把全局变量aa加1000000次。
    thread t2(func1);//创建线程t2,把全局变量aa加1000000次。
    t1.join();
    t2.join();

    cout<<"aa="<<aa<<endl;//显示全局变量aa的值。





}

aa=2000000


已发布

分类

可以收藏大挪耗一下。下载麻烦点城通网盘,站长保证下载速度,不会限速的,放心点就是了;分卷,安卓下载为txt:程序下载为url,不会下载参考不会下载。如果你想让本站活的久一点,请直接捐助

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注