多线程--mutex、原子操作、读写锁

2020-11-01  本文已影响0人  d9e7e8498548

2. 多线程i++(不加锁、mutex、原子操作)

#include <thread>
#include <windows.h>
#include <atomic>

using namespace std;

// unsigned long int g_cnt = 0;
atomic_long g_cnt;

void FuncA()
{
    for (int i = 0; i < 10; ++i) {
        g_cnt++;
        cout << "cnt = " << g_cnt << endl;
        // Sleep(10);
    }
}

void FuncB()
{
    for (int i = 0; i < 10; ++i) {
        g_cnt++;
        cout << "cnt = " << g_cnt << endl;
        // Sleep(5);
    }
}

int main()
{
    thread t1(FuncA);
    thread t2(FuncB);
    // t1.join();
    // t2.join();
    t1.detach();
    t2.detach();
    cout << "cnt = " << g_cnt << endl;
    // Sleep(1000);
    system("pause");
    return 0;
}

参考:

  1. linux的<pthread.h>
  2. C++使用thread类多线程编程
  3. C++ thread用法总结(整理)
  4. C++11中的原子操作(atomic operation)
  5. Linux C++实现多线程同步的四种方式

3. 实现一个读写锁

4. 基于面向对象的思想,实现多线程队列类(基类和子类)

上一篇 下一篇

猜你喜欢

热点阅读