C++多线程

atomic operations library

  • 需要include < atomic > 头文件,标准也定义了命名的完整的atomic类型
Named atomic type equivalent atomic type
atomic_char atomic< char >
atomic_int atomic< int >

等等。

automic<int> 的使用

#include <iostream>
#include <vector>
#include <thread>
#include <functional>
#include <atomic>

void func(std::atomic<int>& counter)
{
    for (int i = 0; i < 10000; ++i) {
        ++counter;
    }
} 

int main()
{
    std::atomic<int> counter(0);
    std::vector<std::thread> threads;

    for (int i = 0; i < 10; ++i) {
        threads.push_back(std::thread{func, std::ref(counter)});
    }

    for (auto& t : threads) {
        t.join();
    }

    std::cout << "Result = " << counter << std::endl;

    return 0;
}

threads with function pointer

#include <iostream>
#include <thread>

using namespace std;

void counter(int id, int numIterations)
{
    for (int i = 0; i < numIterations; ++i) {
        cout << "Counter " << id << " has value ";
        cout << i << endl;
    }
}

int main()
{
    cout.sync_with_stdio(true); // Make sure cout is thread-safe

    thread t1(counter, 1, 6);
    thread t2(counter, 2, 4);
    t1.join();
    t2.join();

    return 0;
}

mutual exclusion

  • mutex classes
  • locks: A lock 是一个包装类,使获取和释放锁变得更加容易。
    • lock_guard 构造函数总是试图获取锁。
    • unique_lock 允许推迟锁的获取时间。

std::call_once

结合std::call_once和std::once_flag来保证一个特定函数或方法只会被调用一次。

condition variable

results matching ""

    No results matching ""