Post

C++ Multithreading

系统整理 C++ 多线程、同步原语、原子操作、条件变量与线程管理

C++ Multithreading
C++系列:第 3 篇,共 6 篇

C++ 标准库和语言特性的用法整理,以及进程间通信

语言与标准库
  1. C++ Containers
  2. C++ Lambda Expressions
  3. C++ Multithreading
  4. C++ Asynchronous Tasks
  5. Formatted Output
通信
  1. ZeroMQ Messaging

在传统的 C++(C++11 之前) 中并没有引入线程这个概念,在 C++11 出来之前,如果想要在 C++ 中实现多线程,需要借助操作系统平台提供的 API,比如 Linux 的<pthread.h> ,或者 Windows 下的<windows.h>
C++11 提供了语言层面上的多线程,包含在头文件<thread> 中。其解决了跨平台的问题,提供了管理线程、保护共享数据、线程间同步操作、原子操作等类。C++11引入了 5 个头文件来支持多线程编程

头文件作用
<thread>提供多线程编程所需的类和函数,包括创建、启动、等待和管理线程
<mutex>提供互斥锁和其他同步原语的类和函数,用于保护共享资源,防止竞态条件
<atomic>提供原子操作库,用于执行线程安全的原子操作
<future>异步编程相关,用于异步执行函数和获取结果,见C++ Asynchronous Tasks
<condition_variable>提供条件变量类,用于线程之间的协调和通信

std::thread

std::thread常用函数

  • 构造&析构函数
函数类别作用
thread() noexcept默认构造函数创建一个不关联任何线程的空对象
template <class Fn, class… Args>
explicit thread(Fn&& fn, Args&&… args)
初始化构造函数创建一个线程
以args为参数
执行fn函数
thread(const thread&) = delete复制构造函数禁用std::thread类的拷贝构造函数
thread(thread&& x) noexcept移动构造函数构造一个与x相同的对象
会破坏x对象
~thread()析构函数析构对象
  • 成员函数
函数作用
void join()等待线程结束并清理资源(会阻塞)
bool joinable()返回线程是否可以执行join函数
void detach()启动的线程自主在后台运行
仅当joinable()为true时可调用,且调用此函数会使其不能被join
std::thread::id get_id()获取线程 id
thread& operator=(std::thread &&rhs)见移动构造函数
(如果对象是joinable,会调用std::terminate()结束程序)

例一:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <iostream>
#include <thread>

void thread1() 
{ 
    std::cout << "Hello," << std::endl; 
}

void thread2() 
{ 
    std::cout << "World!" << std::endl; 
}

int main() 
{
    std::thread a(thread1);
    std::thread b(thread2);

    a.join();
    b.join();

    return 0;
}

输出结果(两个线程间无同步,顺序不定,甚至可能交错):

1
2
Hello,
World!

或者

1
2
World!
Hello,

例二:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <thread>

void countnumber(int id, unsigned int n)
{
    for (unsigned int i = 1; i <= n; i++)
    {
        ;
    }

    std::cout << "Thread " << id << " finished!" << std::endl;
}

int main()
{
    std::thread th[10];
    for (int i = 0; i < 10; i++)
    {
        th[i] = std::thread(countnumber, i, 100000000);
    }

    for (int i = 0; i < 10; i++)
    {
        th[i].join();
    }

    return 0;
}

输出结果之一:

1
2
3
4
5
6
7
8
9
10
Thread 4 finished!
Thread 8 finished!
Thread 6 finished!
Thread 3 finished!
Thread 1 finished!
Thread 7 finished!
Thread 9 finished!
Thread 5 finished!
Thread 2 finished!
Thread 0 finished!

例三:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <thread>

template <class T>
void changevalue(T &x, T val)
{
    x = val;
}

int main()
{
    std::thread th[100];
    int nums[100];
    for (int i = 0; i < 100; i++)
    {
        th[i] = std::thread(changevalue<int>, nums[i], i + 1);
    }

    for (int i = 0; i < 100; i++)
    {
        th[i].join();
        std::cout << nums[i] << std::endl;
    }

    return 0;
}

正常编译这个程序,编译器一定会报错
原因是std::thread会先把参数拷贝一份保存到新线程中,再把这份拷贝作为右值传给函数,而非const的左值引用T &x不能绑定到右值上

要让线程函数拿到原变量的引用,需要用std::ref或std::cref包装参数:

  • std::ref传递可修改的引用
  • std::cref传递const引用

修改代码为

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
#include <iostream>
#include <thread>

template <class T>
void changevalue(T &x, T val)
{
    x = val;
}

int main()
{
    std::thread th[100];
    int nums[100];
    for (int i = 0; i < 100; i++)
    {
        th[i] = std::thread(changevalue<int>, std::ref(nums[i]), i + 1);
    }

    for (int i = 0; i < 100; i++)
    {
        th[i].join();
        std::cout << nums[i] << std::endl;
    }

    return 0;
}

输出结果:

1
2
3
4
5
6
7
1
2
3
4
...
99
100

注意事项:

  • 线程是在thread对象被定义的时候开始执行的,而不是在调用join函数时才执行的,调用join函数只是阻塞等待线程结束并回收资源
  • 分离的线程(执行过detach的线程)会在自己结束时释放资源;但main返回、进程退出时,仍在运行的分离线程会被直接终止
  • 线程会在函数运行完毕后自动释放,不推荐利用其他方法强制结束线程,可能会因资源未释放而导致内存泄漏
  • 没有执行join或detach的std::thread对象在析构时(仍为joinable)会调用std::terminate()终止程序

std::this_thread

在<thread>头文件中,不仅有std::thread这个类,而且还有一个std::this_thread命名空间,其可以很方便地让线程对自己进行控制

std::this_thread常用函数

函数作用
std::thread::id get_id() noexcept获取当前线程 id
template<class Rep, class Period>
void sleep_for( const std::chrono::duration<Rep,
Period>& sleep_duration )
等待sleep_duration
void yield() noexcept暂时放弃线程的执行,将主动权交给其他线程

例四:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <thread>
#include <atomic>
#include <chrono>
#include <cstdint>

std::atomic_bool ready;

void sleep_ms(uintmax_t ms)
{
    std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}
void count()
{
    while (!ready)
        std::this_thread::yield();
    for (int i = 0; i <= 20'0000'0000; i++)
        ;
    std::cout << "Thread " << std::this_thread::get_id() << " finished!" << std::endl;

    return;
}
int main()
{
    ready = 0;
    std::thread th[10];
    for (int i = 0; i < 10; i++)
    {
        th[i] = std::thread(::count);
    }
    sleep_ms(5000);
    
    ready = true;
    std::cout << "Start!" << std::endl;

    for (int i = 0; i < 10; i++)
    {
        th[i].join();
    }

    return 0;
}

输出结果:

1
2
3
4
5
6
7
8
9
10
11
Start!
Thread 139621413664512 finished!
Thread 139621396879104 finished!
Thread 139621371700992 finished!
Thread 139621354915584 finished!
Thread 139621422057216 finished!
Thread 139621380093696 finished!
Thread 139621405271808 finished!
Thread 139621363308288 finished!
Thread 139621346522880 finished!
Thread 139621388486400 finished!

std::mutex 和 std::atomic

std::mutex

std::mutex是 C++ 中最基本的互斥量,一个线程将mutex锁住时,其它的线程就不能操作mutex,直到这个线程将mutex解锁

例五:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <thread>
#include <mutex>

int n = 0;
std::mutex mtx;

void count10000()
{
    for (int i = 1; i <= 10000; i++)
    {
        mtx.lock();
        n++;
        mtx.unlock();
    }
}

int main()
{
    std::thread th[100];
    for (std::thread &x : th)
    {
        x = std::thread(count10000);
    }

    for (std::thread &x : th)
    {
        x.join();
    }

    std::cout << n << std::endl;
    
    return 0;
}

输出结果为 1000000,这里如果不使用锁,实际输出结果比 1000000 小,并且输出结果不定

n++并不是一步完成的,而是读取、加一、写回三步。两个线程的这三步交替执行时,后写回的线程会覆盖掉另一个线程的结果,这种情况称为数据竞争

两个线程同时执行 n++ 时丢失一次更新的过程

std::mutex互斥类型

类型说明
std::mutex基本Mutex类
std::recursive_mutex递归Mutex类
std::timed_mutex定时Mutex类
std::recursive_timed_mutex定时递归Mutex类

std::mutex常用成员函数(mutex 代指对象)

函数作用
void lock()将mutex上锁
如果mutex已经被其它线程上锁,那么会阻塞,直到解锁;
如果mutex已经被同一个线程锁住,为未定义行为(通常表现为死锁),需要重复加锁应使用std::recursive_mutex
void unlock()解锁mutex,释放其所有权
如果有线程因为调用lock()而被阻塞,其中一个线程会获得锁(不保证先后顺序)
如果当前线程未锁定mutex,为未定义行为
bool try_lock()尝试将mutex上锁
如果mutex未被上锁,则将其上锁并返回true,如果mutex已被锁则返回false

std::lock_guard

创建std::lock_guard对象时,它将尝试获取提供给它的互斥锁的所有权。当控制流离开std::lock_guard 对象的作用域时,std::lock_guard析构并释放互斥量

std::lock_guard特点:

  • 创建即加锁,作用域结束自动析构并解锁,无需手工解锁
  • 不能中途解锁,必须等作用域结束才解锁
  • 不能复制

直接调用lock()和unlock()时,如果两者之间提前return或抛出异常,锁将永远不会被释放。使用std::lock_guard可以保证离开作用域时一定解锁,例五中的函数应写成

1
2
3
4
5
6
7
8
void count10000()
{
    for (int i = 1; i <= 10000; i++)
    {
        std::lock_guard<std::mutex> lock(mtx);
        n++;
    }
}

std::unique_lock

std::unique_lock具有std::lock_guard的所有功能,同时又具有其他很多方法,使用起来更加灵活方便,能够应对更复杂的锁定需要

std::unique_lock的特点:

  • 创建时可以不锁定(通过指定第二个参数为std::defer_lock),而在需要时再锁定
  • 可以随时加锁解锁
  • 作用域规则同std::lock_guard,析构时自动释放锁
  • 不可复制,可移动
  • 条件变量需要该类型的锁作为参数(此时必须使用std::unique_lock)
1
2
3
4
5
6
7
std::unique_lock<std::mutex> lock(mtx, std::defer_lock); // 创建时不加锁

lock.lock();   // 需要时再加锁
n++;
lock.unlock(); // 可以提前解锁,缩短持有锁的时间

// 不需要锁的耗时操作

std::scoped_lock

一个线程按A、B的顺序加锁,另一个线程按B、A的顺序加锁,两者各持有一把锁并等待对方释放,就会产生死锁。C++17 提供的std::scoped_lock可以一次锁住多个互斥量,内部使用避免死锁的算法,与书写顺序无关

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <mutex>
#include <thread>

struct Account
{
    std::mutex mtx;
    int balance = 100;
};

void transfer(Account &from, Account &to, int amount)
{
    std::scoped_lock lock(from.mtx, to.mtx); // 同时锁住两个互斥量
    from.balance -= amount;
    to.balance += amount;
}

int main()
{
    Account a, b;

    std::thread th1(transfer, std::ref(a), std::ref(b), 10);
    std::thread th2(transfer, std::ref(b), std::ref(a), 20);

    th1.join();
    th2.join();

    std::cout << a.balance << ' ' << b.balance << std::endl; // 110 90

    return 0;
}

只锁一个互斥量时,std::scoped_lock与std::lock_guard等价

std::shared_mutex

读多写少的场景下,多个线程同时读取并不会产生冲突,用std::mutex会让读线程之间也互相等待。C++17 在<shared_mutex>中提供了读写锁std::shared_mutex:

  • std::shared_lock获取共享锁,多个线程可以同时持有
  • std::unique_lock或std::lock_guard获取独占锁,与其他所有读写线程互斥
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <map>
#include <mutex>
#include <shared_mutex>
#include <string>
#include <thread>
#include <vector>

std::shared_mutex config_mtx;
std::map<std::string, int> config{ {"timeout", 30} };

int read_config(const std::string &key)
{
    std::shared_lock lock(config_mtx); // 共享锁,多个读线程可以同时持有
    return config.at(key);
}

void write_config(const std::string &key, int value)
{
    std::unique_lock lock(config_mtx); // 独占锁
    config[key] = value;
}

int main()
{
    std::vector<std::thread> readers;
    for (int i = 0; i < 4; i++)
    {
        readers.emplace_back([] { read_config("timeout"); });
    }
    std::thread writer(write_config, "timeout", 60);

    for (std::thread &th : readers)
    {
        th.join();
    }
    writer.join();

    std::cout << read_config("timeout") << std::endl; // 60

    return 0;
}

std::call_once

std::call_once配合std::once_flag,保证一个函数在多个线程中只被执行一次,常用于延迟初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <mutex>
#include <thread>

std::once_flag flag;

void init()
{
    std::cout << "init" << std::endl;
}

void worker()
{
    std::call_once(flag, init); // 无论多少个线程调用,init只执行一次
}

int main()
{
    std::thread th[4];
    for (std::thread &x : th)
    {
        x = std::thread(worker);
    }
    for (std::thread &x : th)
    {
        x.join();
    }

    return 0;
}

C++11 起,函数内static局部变量的初始化本身就是线程安全的,单例等场景直接使用static局部变量即可

std::atomic

std::mutex很好地解决了多线程资源争抢的问题,但加锁和解锁都有开销,使用不当还会产生死锁。对于计数器、标志位这样的单个变量,可以改用std::atomic

例六:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <thread>
#include <atomic>

std::atomic<int> n;

void count10000()
{
    for (int i = 1; i <= 10000; i++)
    {
        n++;
    }
}

int main()
{
    n = 0;
    std::thread th[100];
    for (std::thread &x : th)
    {
        x = std::thread(count10000);
    }
    for (std::thread &x : th)
    {
        x.join();
    }

    std::cout << n << std::endl;

    return 0;
}

输出结果同样为 1000000

原子操作是不可分割的操作,其他线程只能看到操作完成之前或完成之后的状态,看不到中间状态

n++对普通变量来说包含读取、加一、写回三步,多个线程交替执行就会丢失更新;对std::atomic<int>来说则是一个原子操作,不需要加锁

注意事项:

  • std::atomic只保证单个操作是原子的,n = n + 1包含一次读取和一次写入,不是原子操作,应写成n++或n += 1
  • 原子变量不能拷贝,也不能用另一个原子变量赋值
  • 需要保护多个变量或一段代码时,仍应使用std::mutex

std::atomic常用成员函数

函数作用
T load()读取当前值
void store(T val)写入新值
T exchange(T val)写入新值并返回旧值
bool compare_exchange_strong(T& expected, T val)当前值等于expected时写入val并返回true
否则把当前值写入expected并返回false
T fetch_add(T val)
T fetch_sub(T val)
加上、减去val并返回旧值(整数和指针类型)

std::atomic构造函数

函数类型作用
constexpr atomic() noexcept(…)默认构造函数构造std::atomic对象
(C++20 起进行值初始化,如std::atomic<int>初值为 0;T的默认构造不抛异常时为noexcept)
constexpr atomic(T val) noexcept初始化构造函数构造一个std::atomic对象
用val的值来初始化
atomic(const atomic&) = delete复制构造函数删除std::atomic类型的拷贝构造函数

condition_variable

<condition_variable>头文件主要包含了与条件变量相关的类和函数
包括:

  • 类
    • std::condition_variable
    • std::condition_variable_any
  • 枚举类型
    • std::cv_status
  • 函数
    • std::notify_all_at_thread_exit()

std::condition_variable必须结合std::unique_lock使用,std::condition_variable_any可以使用任何的锁

std::condition_variable常用成员函数

函数作用
wait(lock)使当前线程等待,直到其他线程通知或唤醒
需要一个已经上锁的std::unique_lock对象作为参数
wait(lock, pred)额外提供一个条件函数
当pred返回false时等待,被唤醒后重新检查
pred:返回true时才返回(可防止虚假唤醒)
notify_one()通知等待在条件变量上的一个线程,使其从等待状态唤醒
notify_all()通知等待在条件变量上的所有线程,使它们从等待状态唤醒

条件变量用于让线程等待某个条件成立:等待的线程在条件不满足时释放锁并休眠,其他线程修改条件后通知它醒来。条件本身必须由互斥量保护,并且等待时要使用带pred的wait,否则可能因虚假唤醒或通知先于等待而出错

例七:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <condition_variable>
#include <iostream>
#include <mutex>
#include <queue>
#include <thread>

std::mutex mtx;
std::condition_variable cv;
std::queue<int> tasks;
bool finished = false;

void producer()
{
    for (int i = 1; i <= 5; i++)
    {
        {
            std::lock_guard<std::mutex> lock(mtx);
            tasks.push(i);
        }
        cv.notify_one(); // 先解锁再通知,被唤醒的线程可以立即拿到锁
    }

    {
        std::lock_guard<std::mutex> lock(mtx);
        finished = true;
    }
    cv.notify_all();
}

void consumer()
{
    while (true)
    {
        std::unique_lock<std::mutex> lock(mtx);
        cv.wait(lock, [] { return !tasks.empty() || finished; }); // 等待期间自动释放锁

        if (tasks.empty())
        {
            break; // 队列已空且生产结束
        }

        int task = tasks.front();
        tasks.pop();
        lock.unlock(); // 处理任务时不需要持有锁

        std::cout << "task " << task << std::endl;
    }
}

int main()
{
    std::thread th1(producer);
    std::thread th2(consumer);

    th1.join();
    th2.join();

    return 0;
}

输出结果:

1
2
3
4
5
task 1
task 2
task 3
task 4
task 5

thread_local

用thread_local声明的变量在每个线程中各有一份独立的副本,线程之间互不影响,不需要加锁。常用于每个线程各自的缓存、计数器、随机数生成器等

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <mutex>
#include <thread>

thread_local int counter = 0; // 每个线程各有一份
std::mutex print_mtx;

void work(int id)
{
    for (int i = 0; i < 1000 * id; i++)
    {
        counter++; // 只修改当前线程的副本,不需要加锁
    }

    std::lock_guard<std::mutex> lock(print_mtx);
    std::cout << "thread " << id << ": " << counter << std::endl;
}

int main()
{
    std::thread th1(work, 1);
    std::thread th2(work, 2);

    th1.join();
    th2.join();

    std::cout << "main: " << counter << std::endl; // main: 0

    return 0;
}

两个线程分别输出 1000 和 2000,主线程的counter仍为 0

std::jthread

C++20 在<thread>中新增了std::jthread,与std::thread相比有两点改进:

  • 析构时自动join,不会因为忘记join而调用std::terminate()
  • 内置停止机制,线程函数的第一个参数为std::stop_token时,可以通过request_stop()请求线程退出

例八:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <chrono>
#include <iostream>
#include <thread>

void worker(std::stop_token token)
{
    while (!token.stop_requested())
    {
        std::cout << "working" << std::endl;
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }

    std::cout << "stopped" << std::endl;
}

int main()
{
    std::jthread th(worker);

    std::this_thread::sleep_for(std::chrono::milliseconds(350));
    th.request_stop(); // 请求线程退出

    return 0; // 析构时自动join
}
This post is licensed under CC BY 4.0 by the author.