C++ Boost::Thread

Thread

Thread是Boost库中进行平台无关的线程调用对象

Thread 线程
mutex 互斥量
_lock RAII锁

condition_variaty 条件表达式
barrier屏障 latch锁存器
Future Promise Packaged_task

线程管理

启动线程

向 boost::thread 对象中传入一个函数对象。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
struct callable_test
{
std::string str;
callable_test() { str = ""; }
callable_test(std::string s) { str = s; }
void operator()(int n = 1)
{
for(int i = 0; i < n; ++i)
{
std::cout << i << '\t' << str << std::endl;
}
return;
}
};

callable x;

boost::thread th1(x);

对于以下操作会导致 undefined 行为

1
2
3
4
5
6
7
8
9
10
11
12
boost::thread func()
{
callable x;
return boost::thread(boost::ref(x)); // 采用引用进行函数对象的传入
} // 函数对象的生命周期结束

int main()
{
boost::thread th = func();

th.join(); // 此时,引用指向了空,导致行为未定义
}

由此,注意,若传入的对象无法进行拷贝传入 ,那么由于引用的语义特性,需要 引用传入的对象的 生命周期 长于该被创建线程的生命周期。

在创建线程时,传入函数对象,并可以传入所需参数,且传入的参数数量并未有所限制

1
2
3
boost::thread th(func, a1, a2, a3, a4);

boost::thread th(boost::ref(func), a1, a2, a3, a4);

线程函数的异常

若,向 boost::thread 的构造函数 传入的函数对象,在调用时出现了异常,则,该异常并不是 boost::interrupted类型 而是调用 std::terminate()

分离线程

使用 .detach() 在 boost::thread 对象上 进行线程分离,此时,该线程不再受主线程的限制,而是从主线程分离,又系统进行控制,其执行内容永远正确时可以使用。

1
th.detach();

调用后, boost::thread 对象表现为 非线程 ,在调用 get_id() 后返回 {Not-any-thread} ,即为不由其原所在的主线程管理。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void test4()
{
callable_test x("This is x.");
callable_test y("This is y.");

boost::thread th1(x, 10);
boost::thread th2(y, 10);

th1.detach(); // 分离线程

Sleep(100);

std::cout << "x get_id() " << th1.get_id() << std::endl; // {Not-any-thread}
return;
}

加入线程

为使主线程等待子线程加入,需要调用 join() try_join_for() try_join_until() 来让主线程等待子线程返回, timed_join() 已被弃用。

以上三个调用,都将 阻塞调用线程 直到子线程对象完成。

1
2
3
4
5
6
7
8
9
10
11
void test5()
{
callable_test x("This is a thread to test join().");
boost::thread th(x, 15);

th.join();

std::cout << "The thread has joined.\n";

return;
}

以上调用,在运行时,最后的 std::cout 一定是在 所有的线程信息打印后输出的。

对于 try_join_for() 与 try_join_until() 的调用,则为指定时间后若未完成则强制进行线程加入,将子线程返回。

try_join_for(boost::chrono::) 是等待 一段时间 若该时间内,子线程已经返回,则直接返回,若超出该设定时间,则子线程在超时时直接返回。设定了子线程的允许可运行时间。

try_join_until(boost::chrono::timepoint) 是等到 某个时间点 ,子线程直接返回。设定了子线程在何确定时刻会结束。

对于 join 操作,还有一个 joinable() 方法,一般与 join() 搭配使用,其检测是否可以进行 join 操作,可以进行 join 则返回 true 。当然,若 boost::thread 对象是 非线程 时,其不可执行 join() ,且 加入过的线程对象 必然无法再次进行 join() 操作。

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
void test6()
{
callable_test x("This is for testing try_join_for().\n");

boost::thread th(x, 25);

if (th.try_join_for(boost::chrono::microseconds(100)))
{
std::cout << "try join for 10ms.\nsub thread returned.\n";
}

callable_test y("This is for testing try_join_until().\n");

boost::thread th2(y, 20);

boost::chrono::steady_clock::time_point tp = boost::chrono::steady_clock::now();
if (th2.try_join_until(tp + boost::chrono::microseconds(100)))
{
std::cout << "try join at now() + 100ms.\nsub thread returned.\n";
}

callable_test z("This is for testing joinable().\n");

boost::thread th3(z, 100);

if (th3.joinable())
{
th3.join();
}
}

关于 boost::thread 对象的析构

可以使用 boost::thread_joiner 来确保子线程在 析构之前 执行线程加入调用线程。

1
2
3
4
5
6
int main()
{
boost::thread t(my_func);
boost::thread_joiner g(t);
// do something else
} // here the thread_joiner destructor will join the thread before it is destroyed.

因为,在 boost::thread 对象销毁时,并不会等待函数对象的加入,而是将 线程分离 将该函数对象与线程对象分离,在传入的可调用函数调用结束后或程序结束后才被系统回收。(在我使用的版本中好像没用对应的 boost::thread_joiner 内容)

关于 boost::thread_joiner 现代C++使用RAII范式进行实现,如下列代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class thread_guard {
boost::thread& t_;
public:
explicit thread_guard(boost::thread& t) : t_(t) {}
~thread_guard() {
if(t_.joinable()) {
t_.join();
}
}
// 禁止拷贝
thread_guard(const thread_guard&) = delete;
thread_guard& operator=(const thread_guard&) = delete;
};

int main() {
boost::thread t(my_func);
thread_guard g(t);
// 作用域结束时自动join
}

中断

可以调用 boost::thread 对象中的 interrupt() 成员函数来中断正在执行的线程。

与其他异常不同,当 boost::thread_interrupted 从线程主函数中传播出来时,这不会导致调用 std::terminate;效果就像线程主函数已正常返回一样。即,若不在主函数中使用异常捕获时,其并不抛出异常。

在函数对象中 调用 boost::this_thread::interruption_point() 来 标记中断点 。显示检查中断点。

在函数中可以通过 声明 boost::this_thread::disable_interruption disable; 来保证该线程 不被中断 。但是中断请求仍会被记录。

可以在函数中 调用 boost::this_thread::interruption_enabled() 来检查该线程是否允许被中断,当声明了 上一条的对象 obj 时,其返回值为 false 。

为了 反转 线程可中断状态,可以 声明 boost::this_thread::restore_interruption restore(disable); 来反转上一条 boost::this_thread__disable_interruption 对象的状态,让其后的语句进入 可中断状态 。通常会使用 { } 一个暂时块,来进行处理,在出块后 restore 被析构,线程状态回到原有的状态。当然,若 disable 也在一个暂时块中,线程的 不可中断 也是暂时的。

若在 disable 的作用时间内其 boost::thread 对象若使用了 interrupt() 方法,则其 中断信号 仍被记录,但是并不会立即中断线程。在后来若声明了 restore 则线程变为 可中断状态 若有 中断记录 则直接中断。

可以使用 boost::this_thread::interruption_requested() 来检查,该线程是否接收到过 中断信号 ,一般在 disable 的作用时间进行调用。因为,若在 restore 后,则有可能该线程早已中断。

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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
void test7()
{
boost::thread th([]() -> void{
boost::this_thread::disable_interruption disable_interrupt; // this object can control if this thread can be interrupted

std::cout << "has interruption_point() next line.\n";
if (boost::this_thread::interruption_enabled()) // check if this thread can be interrupted
{
std::cout << "This thread can be interrupted.\n";
}

boost::this_thread::interruption_point(); // if disable_interruption object is exiting will not be interrupted
std::cout << "has no interruption, this thread's id is " << boost::this_thread::get_id() << std::endl;
});

boost::this_thread::sleep_for(boost::chrono::seconds(1));
th.interrupt();

th.join();

boost::thread th2([]() -> void {
try
{
std::cout << "\nIn try block.\n";

for(int i = 0; i < 10; ++i)
{
std::cout << "Work" << i << "..." << std::endl;
boost::this_thread::sleep_for(boost::chrono::seconds(1));

// boost::this_thread

boost::this_thread::interruption_point(); // set intrruption point
if (boost::this_thread::interruption_enabled()) // if enable to interrupt
{
std::cout << "enable to interrupt.\n";
}
}
}
catch (boost::thread_interrupted&)
{
std::cout << "throw boost::thread_interrupted.\n";
}
});

boost::this_thread::sleep_for(boost::chrono::seconds(3));
th2.interrupt();

th2.join();

boost::thread th3([]() -> void {
{
if(boost::this_thread::interruption_enabled())
{
std::cout << "\nget into a block.\nNow this thread CAN BE interrupted.\n";
}

boost::this_thread::disable_interruption disable_interruption;
if (!boost::this_thread::interruption_enabled())
{
std::cout << "\nthis thread CAN NOT BE interrupted NOW.\n";
}
{
boost::this_thread::restore_interruption restore(disable_interruption);
if (boost::this_thread::interruption_enabled)
{
std::cout << "\nthis thread CAN BE interrupted.\n";
}
}

if(!boost::this_thread::interruption_enabled())
{
std::cout << "\nthis thread CAN NOT BE interrued.\n";
}
}

if (boost::this_thread::interruption_enabled())
{
std::cout << "\nOUT OF ALL BLOCK IN ORIGIN SPACE.\nCAN BE INTERRUPTED.\n";
}
});

th3.join();

boost::thread th4([]() -> void {
boost::this_thread::disable_interruption di;
std::cout << "\nDo some important work can not be interrupted.\n";
boost::this_thread::sleep_for(boost::chrono::seconds(1));

if (boost::this_thread::interruption_requested())
{
std::cout << "Get a interruption signal.\n";
}
// if get a interruption signal the code under the 're' will not be executed
boost::this_thread::restore_interruption re(di);
if (!boost::this_thread::interruption_requested())
{
std::cout << "Get no interruption signal.\n";
}
});
th4.interrupt();

th4.join();
}
  • 预定义中断点

    以下函数是中断点,如果为当前线程启用中断,并且为当前线程请求中断,则它们将抛出 boost::thread_interrupted

    • boost::thread::join()
    • boost::thread::timed_join()
    • boost::thread::try_join_for()
    • boost::thread::try_join_until()
    • boost::condition_variable::wait()
    • boost::condition_variable::timed_wait()
    • boost::condition_variable::wait_for()
    • boost::condition_variable::wait_until()
    • boost::condition_variable_any::wait()
    • boost::condition_variable_any::timed_wait()
    • boost::condition_variable_any::wait_for()
    • boost::condition_variable_any::wait_until()
    • boost::thread::sleep()
    • boost::this_thread::sleep_for()
    • boost::this_thread::sleep_until()
    • boost::this_thread::interruption_point()

线程ID

boost::thread::id 类的对象可用于标识线程。 每个正在运行的执行线程都有一个唯一的 ID,可以从相应的 boost::thread 通过调用 get_id() 成员函数获得,或者通过从线程内部调用 boost::this_thread::get_id() 获得。boost::thread::id 类的对象可以复制,并用作关联容器中的键:提供了全范围的比较运算符。 线程 ID 也可以使用流插入运算符写入输出流,但输出格式未指定。

boost::thread::id 的每个实例要么引用某个线程,要么引用 非线程 Not-any-thread。 引用 非线程 的实例彼此比较相等,但不等于引用实际执行线程的任何实例。 boost::thread::id 上的比较运算符为每个不相等的线程 ID 产生一个全序。

boost::thread::中的其他内容

boost::thread::hardware_concurrency() 该方法为静态方法,返回当前系统上可用的硬件线程数(例如,CPU 或核心或超线程单元的数量),如果此信息不可用,则为 0。

boost::thread::physical_concurrency() 该方法为静态方法,返回当前系统上可用的物理核心数。与 hardware_concurrency() 相比,它不返回虚拟核心的数量,而仅计数物理核心。

boost::thread::native_handle() 返回 native_handle_type 的实例,该实例可以与平台特定的 API 一起使用,以操作底层实现。如果不存在此类实例,则 native_handle() 和 native_handle_type 不存在。

关于boost::this_thread中的内容

上文的内容中已经提到过关于 中断控制 的内容。

可以对本线程信息进行操作。当然,对于入口函数 int main() 也具有操作能力。

注意 this_thread 只是一个 命名空间

yield() 函数,放弃当前线程剩余的时间片,以允许其他线程运行。可以避免一个线程过多的占用CPU的流水线时间。而非使用类似于 sleep_for() 的计时函数,占用CPU资源,让程序陷入一个忙等待状态,高强度占用CPU时间。也就是让该线程放弃对CPU的占用,释放这一部分的资源,让其他的线程 有机会竞争该时间片资源 。但,让出的操作,也会产生资源开销,最好不要频繁的调用该函数,只在关键优化部分进行调用。

yield() 仅仅是 让出时间片 ,可能在让出后,仍没有其他可用线程被CPU接收执行,此时CPU相对空闲,所以,该线程可能会直接回到CPU调度的时间片中执行。

  • 其主要的价值在于
    1. 减少CPU竞争:在自旋锁、CAS循环等高竞争场景中减少总线争用
    2. 提高系统响应性:让等待的线程主动让出CPU,使其他线程能更快响应
    3. 实现协作式调度:在计算密集型任务中穿插yield,提高整体吞吐量
    4. 节能:减少不必要的忙等待,降低CPU使用率

at_thread_exit(Callable func) 函数,传入一个函数对象func,func 的副本被放置在线程特定的存储中。当当前线程退出时,将调用此副本(即使线程已被中断)。也就是标识当前线程推出后需要执行的功能操作。

1
2
3
4
5
6
7
8
9
10
void test8()
{
boost::this_thread::at_thread_exit([]() -> void {
std::cout << "test8() thread is over.\n" << "Thread id: " << boost::this_thread::get_id() << std::endl;
});

std::cout << "can be used hardware thread: " << boost::thread::hardware_concurrency() << std::endl;
std::cout << "can be used physical core: " << boost::thread::physical_concurrency() << std::endl;

}

关于thread_group类

thread_group 提供了一个以某种方式相关的线程集合。可以使用 add_thread 和 create_thread 成员函数将新线程添加到组中。thread_group 不可复制或移动。

仅有一个空参的构造函数,创建为一个空的线程组集合。

create_thread(Func F) 在线程组中,创建一个线程,其传参形式与 new boost::thread(); 一致。

add_thread(boost::thread thrd)* 在线程组中,以对象指针的形式加入一个线程。获取由 thrd 指向的 boost::thread 对象的 所有权 ,并将其添加到组中。一般传入 new thread() ,或传入一个指向线程对象的指针。

remove_thread(boost::thread thrd)* 在线程组中将 thrd 移除,但并不调用 delete 。

size() 则是该线程组中所包含的线程数。

this_thread_in() 该线程组调用时所处的线程是否在线程组中。

is_this_thread_in(boost::thread thrd)* 线程指针thrd所指向的线程对象是否处于该线程组中。

作用域线程

#include <boost/thread/scoped_thread.hpp>

作用域线程是线程的 包装器 ,允许用户在销毁线程时执行什么操作。常见的用途是在销毁时 加入(join) 线程,因此这是 默认行为 。这是与线程唯一的区别。即,当线程在析构函数中调用 std::terminate() 若线程是可加入的, strict_scoped_thread<> 和 scoped_thread<> 会在线程 joinable() 则 join() 该线程。

关于构造函数

boost::scoped_thread 为 boost::joining_thread 的别名。

boost::scoped_thread(boost::thread&& thrd) 接收一个左值原始boost线程对象。

boost::scoped_thread(F&&, Args…) 接收一个 函数对象 及 传入参数 。

有一个默认空参构造函数,一个移动构造函数。

boost::strict_scoped_thread(boost::thread&& thrd) 接收一个左值原始boost线程对象。

boost::strict_scoped_thread(F&&, Args…) 接受一个 函数对象 及 传入参数 。

关于 strict_scoped_thread 的构造函数仅有以上两种方式。

boost::strict_scoped_thread 和 boost::scoped_thread 的区别在于, strict_scoped_thread 隐藏了拥有的线程,无可对线程进行操作的方法。仅包含了构造与析构。

boost::scoped_thread 对象的成员函数与 boost::thread 的成员函数一致。

自由线程仿函数

仿函数 detach

1
2
3
4
5
6
7
struct detach
{
operator()(boost::thread& t)
{
t.detach();
}
}

仿函数 join_if_joinable

1
2
3
4
5
6
7
8
9
10
struct join_if_joinable
{
operator()(boost::thread& t)
{
if(t.joinable())
{
t.join();
}
}
}

仿函数 interrupt_join_if_joinable

1
2
3
4
5
6
7
8
9
10
11
struct interrupt_join_if_joinable
{
operator()(boost::thread& t)
{
t.interrupt();
if(t.joinable())
{
t.join();
}
}
}

以上的仿函数可以作为模板参数传入 boost::scoped_thread<CallableThread = boost::join_if_joinable, Thread = boost::thread> boost::strict_scoped_thread<CallableThread = boost::join_if_joinable, Thread = boost::thread> 的模板参数中。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
void test2()
{
{
boost::scoped_thread<boost::detach> sc_thrd(boost::thread(callable_test("MSG"), 1000));
}
{
boost::strict_scoped_thread<boost::interrupt_and_join_if_joinable> s_sc_thrd(boost::thread(callable_test("This is a simple test. strict."), 100));
}
{
boost::scoped_thread<boost::join_if_joinable> sc_t(boost::thread(callable_test("Another test."), 100));
}

boost::this_thread::sleep_for(boost::chrono::seconds(1));
}

后两个作用域内的函数完全不会相互竞争,而 sc_thrd 对象在出作用域后,线程分离,所处线程不管理该线程,原线程对象转为自由线程。即, sc_thrd 对象管理的线程在析构分离后仍参与往后的线程竞争且不会受主线程处理。

同步 synchronolization

Locking in C++

Mutex, Lock, Condition Variable Rationale

一个中断,就是线程不再占用CPU时间,等待程序再次调起。即,非忙等待。
以下的 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
class count_test
{
private:
int count;
boost::mutex mtx;

public:
count_test()
: count(0) {}

count_test(int cunt)
: count(cunt) {}

public:
void auto_asc() {
mtx.lock();

++count;

mtx.unlock();
}

void auto_desc() {
boost::lock_guard<boost::mutex> lock_g(this->mtx);
--count;
}

void turn_zero() {
boost::lock_guard<boost::mutex> lock_g(this->mtx);
count = 0;
}

void add(int value) {
boost::lock_guard<boost::mutex> lock_g(this->mtx);
count += value;
}

void diff(int value) {
boost::lock_guard<boost::mutex> lock_g(this->mtx);
count -= value;
}

const int get_count_value() {
boost::lock_guard<boost::mutex> lock_g(this->mtx);
return this->count;
}
};

在并发任务中,若存在多个读取与写入,由于线程竞争的问题,极可能会存在内存操作混乱以及其他不安全的状况。

此时,可以使用 互斥量mutex 来保证 独占访问 。互斥量是获取 同步 的简单而基本的机制。

在具有多个 并发对象 和多个 共享对象 的系统中,可能很难通过互斥量来描述同步。大量的互斥量的加入,可能会导致程序 难以阅读和编写 。所以将引入通用类来处理更复杂的同步和通信形式。

使用 RAII 的习惯,通过一个包装的 作用域锁 来简化很多编写需要。即 lock_guard 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
void test5()
{
const int N = 1'000'000;

count_test count(0);

boost::thread_group thrd_g;

for (int i = 0; i < 5; ++i)
{
thrd_g.add_thread(new boost::thread([&count](const int N) -> void {
for(int k = 0; k < N; ++k)
{
count.auto_asc();
}
}, N));
}

thrd_g.join_all();

std::cout << "count_test.count = " << count.get_count_value() << std::endl;
}

boost::mutex

lock() unlock() 两个成员方法,进行加锁的解锁,注意,在对一组并发对象与共享对象系统中的加锁与解锁需要的是 唯一一个 boost::mutex 对象 。如,以下的 test3() 函数中的线程传入的用于循环的Labmda函数,不在各个线程中创建各自的互斥量,而是使用 共享的互斥量 来处理线程的同步。

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
void test3()
{
const int N = 100'000;
int count = 0;

boost::thread_group thrd_g;
boost::mutex mtx;

for (int i = 0; i < 5; ++i)
{
thrd_g.add_thread(new boost::thread([&count, &mtx](int n) -> void {

for (int i = 0; i < n; ++i)
{
mtx.lock();
++count;
mtx.unlock();
}

}, N));
}

thrd_g.join_all();

std::cout << "count value: " << count << std::endl;
}

void test4()
{
const int N = 1'000'000;
int count = 0;

boost::thread_group thrd_g;
boost::mutex mtx;

for (int i = 0; i < 5; ++i)
{
thrd_g.add_thread(new boost::thread([&count, &mtx](int n) -> void {
for (int i = 0; i < n; ++i)
{
boost::lock_guard<boost::mutex> lock_g(mtx);
++count;
}
}, N));
}

thrd_g.join_all();

std::cout << "count value: " << N << std::endl;

}

try_lock() try_lock_for() try_lock_until() timed_lock() 是尝试进行线程的加锁,分别是 尝试加锁,在一定时间内可否加锁,在什么时刻可以加锁,什么时间后加锁。

initialize() destory() 方法是暴露的对 boost::mutex 进行手动 初始化 销毁 的低级接口,可以用此控制 互斥量的生命周期 。构造时使用 initialize() 析构时调用 destory() 。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
void correct_pattern() {
boost::mutex mtx;

mtx.initialize(); // ✅ 必须在使用前初始化

{
boost::lock_guard<boost::mutex> lock(mtx); // ✅ 正常使用
}

mtx.destroy(); // ✅ 使用后销毁
}

void dangerous_pattern() {
boost::mutex mtx;

// mtx.lock(); // ❌ 危险:未初始化就使用

mtx.initialize();
mtx.lock(); // ✅ 安全
mtx.unlock();
mtx.destroy();

// mtx.lock(); // ❌ 危险:销毁后使用
}

在 lock_guard 这个互斥量包装器中,其对作用域内的自动管理也是这样,lock_guard()构造时调用 mutex.lock() 其 ~lock_guard() 析构函数中调用 mutex::unlock() 。

关于 lock_guard 类,它暴露出来的方法除了 ~lock_guard() 析构函数 并没有其他可操作的方法,所以可能在某些情况下,会需要使用 { } 作用域 进行对 lock_guard 锁的作用域限定。

内部和外部锁定

内部与外部则是 锁 相对于 资源 的位置,在资源内部调用则为 内部锁 ,在资源外进行显示调用则为 外部锁 ,由 程序员进行处理 。

使用内部锁定的类保证对其公共成员函数的任何并发调用 都不会破坏该类的实例 。这通常通过让每个 公共成员函数 在 进入时获取对象的锁 来确保。 这样,对于该类的任何给定对象,在任何时候只能有一个成员函数调用处于活动状态,因此操作可以很好地序列化。(对同一字段的 写 读 操作的公共成员函数)

对于许多现实生活中的同步任务,内部锁定是不够的。如,若严格按 先增加 后减少 的顺序进行(如,在银行进行取钱及其扣除手续费的操作,两个操作之间不能出现其他操作)。

现在修改一下 count_test 的类实现

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
class count_test
: public boost::basic_lockable_adapter<boost::recursive_mutex>
{
private:
int count;

public:
count_test()
: count(0) {}

count_test(int cunt)
: count(cunt) {}

public:
void auto_asc() {
boost::lock_guard<count_test> mtx(*this);
++count;
}

void auto_desc() {
boost::lock_guard<count_test> mtx(*this);
--count;
}

void turn_zero() {
boost::lock_guard<count_test> lock_g(*this);
count = 0;
}

void add(int value) {
boost::lock_guard<count_test> lock_g(*this);
count += value;
}

void diff(int value) {
boost::lock_guard<count_test> lock_g(*this);
count -= value;
}

const int get_count_value() {
boost::lock_guard<count_test> lock_g(*this);
return this->count;
}
};

使其 继承 basic_lockable_adaperboost::recursive_mutex 类,其中的 boost::recursive_mutex 类模板参数是一个 可递归的 mutex 版本 以保证同一线程多次获取 相同互斥量 时 不会发生阻塞 。

<boost/thread/recursive_mutex.hpp>
<boost/thread/lockable_adapter.hpp>

basic_lockable_adaper类 相当于一个适配器,可以将其派生类本身作为一个 互斥量 进行处理。其实就是为派生类提供了一对公共的 lock() 和 unlock() 操作。其类实现中,应该也重载了与 原 boost::mutex 类进行类型转换的方法。大概就是从类中提取出作为成员的 boost::mutex 对象(继承于 boost::basic_lockable_adaper 类的)

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
void add_then_diff(count_test& count, int add, int diff)
{
boost::lock_guard<count_test> mtx(count);
count.add(add);
count.diff(diff);
}

void test6()
{
const int N = 5;
const int origin_value = 10000;
count_test record(origin_value);

boost::thread_group thrd_g;

for (int i = 0; i < N; ++i)
{
thrd_g.add_thread(new boost::thread([&record](int add, int diff) -> void {
add_then_diff(record, add, diff);
}, 1000, 100));
}

thrd_g.join_all();

std::cout << "record's origin value is " << origin_value << std::endl;
std::cout << "record after add 1000 then diff 100 for 5 times is " << record.get_count_value() << std::endl;
}

若使用原来的 count_test类 进行处理,由于存在两组对同一互斥量的调用,虽然先后关系是确定的,但是,无法保证在两个操作中间不会有其他的任务 竞争到这个互斥锁 。

以下为外部锁定的多线程类定义方法。 由于公共继承了一个 boost::basic_lockable_adapterboost::mutex 类,(在这没有传入 boost::rescursive_mutex 是因为类内成员函数没有使用锁的需要)该派生类会继承一组父类中定义的 lock() unlock() 方法,进行加锁与解锁操作。可以在客户端代码中直接使用 count_test 类对象(如 count_test声明了一个 count对象),count.lock() …task… count.unlock() 。

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
**class count_test
: public boost::basic_lockable_adapter<boost::mutex>
{
private:
int count;

public:
count_test()
: count(0) {}

count_test(int cunt)
: count(cunt) {}

public:
void auto_asc() {
++count;
}

void auto_desc() {
--count;
}

void turn_zero() {
count = 0;
}

void add(int value) {
count += value;
}

void diff(int value) {
count -= value;
}

const int get_count_value() {
return this->count;
}
};**

若在设计 多线程类 时采用 内部锁定 ,则会使自己面临 效率低下 或 死锁 的风险。若依赖于调用者提供的锁定,则会使类难以使用。而使用外部锁定的方法,将锁留给客户端代码就可以避免以上问题。
但是,调用者管理锁定的方法,客观上确实会产生隐性的安全问题。

外部锁定 —— strict_lock 和 externally_lock 类

<boost/thread/strict_lock.hpp>
<boost/thread/externally_lock.hpp>

  • boost::strict_lock (增强于lock_guard)

    严格持有锁,且 不能被手动解锁或重新锁定 ,确保了在持有锁的整个作用域内(及其子作用域内,线程得以安全维持)

    其有两个重载的构造函数:

    • 引用传入一个 type 类的对象(常用)
    • 传入一个 lockable_wrapper 类的初始化序列,(如,lock_guard)

    mutex() 返回一个指向其中 互斥量 成员的 指针

    owns_lock() 返回一个 bool 值,检测是否持有一个锁,可以传入一个指向 type 类的指针,或空。此函数为 非静态函数 。

  • boost::externally_lock

    其有三个重载的构造函数:

    • 引用传入一个 互斥量 boost::mutex 对象
    • 引用传入 互斥量 boost::mutex 对象, 右值引用 type 类对象(可以使用移动语义)
    • 引用传入 互斥量 boost::mutex 对象, 引用传入需要锁定的 type 类对象

    get() 返回一个对其中锁所包含的 type 类对象的 常量引用

    mutex() 返回一个指向其中 互斥量 成员的 指针

    lock() try_lock() unlock() 与 boost::mutex 功能一致

  • 将锁作为许可证

    对于会有 高并发读写 需求的对象,理想情况下,应该能够执行以下的操作:

    • 支持两种锁定模型(内部和外部)
    • 高效;不使用不必要的锁定。
    • 安全;未经适当的锁定无法操作相应对象。

    从之前的 继承了 boost::basic_lockable_adapterboost::mutex 的 count_test类 对象(object),都可以通过 boost::lock_guard 直接进行对象的锁定。

    可以将 boost::lock_guard 对象视为锁并使用它作为 许可证 。拥有 lock_guard 可以有权执行某些操作。 lock_guard 对象 不应该被复制或别名(它不是可传递的许可证) 。

    1. 只要许可证仍然有效, object 对象就会 保持锁定状态
    2. 当 lock_guard 被销毁时, object 的 互斥锁将被释放 。

    最终,可以在代码中的任何部分, 只要 拥有一个 lock_guard对象 就能 保证一个 object 被锁定 。但是无法确切的知道是 哪个 count_test 对象被锁定

    此时,对 lock_guard类模板进行增强 。并将其增强后的版本称为 strict_lock 。本质上,strict_lock 的作用仅仅作为自动变量存在于 栈 上。 strict_lock 必须遵循非复制和非别名策略 。

    • 只能从一个 有效的 T 对象开始创建 boost::strict_lock 。

    • 可以通过 引用 将 boost::strict_lock 传递给函数或从函数返回。

      1
      2
      boost::strict_lock<T>& Foo();
      void Foo(boost::strict_lock<T>&);

    以上这些规则都是为了一个目的 —— 强制保证拥有一个 boost::strict_lock 意味着

    1. 锁定了一个 T 对象
    2. 该对象 稍后会被解锁

    lock_guard 实际上并不是直接锁定 BankAccount类对象,而是锁定了与这个BankAccount关联的互斥量,而关联是在外部维护的,从 类型系统上看 ,程序员只知道这个锁是用于 BankAccount类型 的资源,但不知道哪个具体实例。

    • 关于为什么指的是类型系统层面的不确定性(抽象设计,模板设计)

      • 模板化的设计模式

        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
        // 假设 BankAccount 支持外部锁定,即有 lock() 和 unlock() 方法
        class BankAccount {
        private:
        boost::mutex mtx_;
        double balance_;

        public:
        void lock() { mtx_.lock(); }
        void unlock() { mtx_.unlock(); }

        void deposit(double amount) {
        // 不需要内部加锁,由外部锁定控制
        balance_ += amount;
        }

        void withdraw(double amount) {
        balance_ -= amount;
        }
        };

        // 模板函数 - 这里就是手册中提到的场景
        template<typename Lockable>
        void process_account(Lockable& account) {
        boost::lock_guard<Lockable> lock(account); // ⚠️ 这里!

        // 我们知道 account 被锁定了,但不知道具体是哪个账户
        // 因为 Lockable 可能是任何支持锁定的类型
        account.deposit(100.0);
        }

        // 使用示例
        void example() {
        BankAccount checking_account;
        BankAccount savings_account;

        process_account(checking_account); // 锁定 checking_account
        process_account(savings_account); // 锁定 savings_account

        // 在 process_account 函数内部,我们不知道具体锁定的是哪个账户
        }
      • 多态场景中的不确定性

        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
        class Account {
        public:
        virtual void lock() = 0;
        virtual void unlock() = 0;
        virtual void process() = 0;
        virtual ~Account() = default;
        };

        class CheckingAccount : public Account {
        boost::mutex mtx_;
        public:
        void lock() override { mtx_.lock(); }
        void unlock() override { mtx_.unlock(); }
        void process() override { /* 处理支票账户 */ }
        };

        class SavingsAccount : public Account {
        boost::mutex mtx_;
        public:
        void lock() override { mtx_.lock(); }
        void unlock() override { mtx_.unlock(); }
        void process() override { /* 处理储蓄账户 */ }
        };

        void process_any_account(Account& account) {
        boost::lock_guard<Account> lock(account); // ⚠️ 这里!

        // 我们知道 account 被锁定了,但不知道具体类型
        // 可能是 CheckingAccount,也可能是 SavingsAccount
        account.process();
        }

        void usage() {
        CheckingAccount checking;
        SavingsAccount savings;

        process_any_account(checking); // 锁定支票账户
        process_any_account(savings); // 锁定储蓄账户
        }
      • 容器中的账户处理

        1
        2
        3
        4
        5
        6
        7
        8
        9
        10
        11
        12
        13
        14
        15
        16
        17
        18
        19
        20
        void process_accounts(std::vector<BankAccount>& accounts) {
        for (auto& account : accounts) {
        boost::lock_guard<BankAccount> lock(account); // ⚠️ 这里!

        // 我们知道某个 BankAccount 被锁定了
        // 但不知道是向量中的第几个账户
        account.deposit(50.0);
        }
        }

        // 或者更复杂的情况
        template<typename AccountContainer>
        void bulk_process(AccountContainer& accounts) {
        for (auto& account : accounts) {
        boost::lock_guard<decltype(account)> lock(account);

        // 我们只知道 account 被锁定,但不知道具体细节
        account.process_transaction();
        }
        }
    • 如何使用 boost::strict_lock 来为 BankAccount 定义一个安全、灵活的接口:

      • 为其中的每个接口函数编写 两个重载
      • 一个版本保持与之前相同的签名,另一个版本时接收一个额外的 boost::strict_lock 类型参数。第一个版本提供内部锁定;第二个版本 需要外部锁定 。通过要求 客户端代码 创建一个 strict_lock 对象,在编译时 强制执行外部锁定 。
      • BankAccount 通过让内部锁定的函数 转发 到外部锁定的函数来 避免代码膨胀 ,外部锁定的函数完成实际的工作。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    void add(int value, boost::strict_lock<count_test>& strict_l) // outter lock
    {
    // not need to write an internally lock
    count += value;
    }
    void add(int value) {
    boost::lock_guard<count_test> lock_g(*this); // internally lock
    count += value;
    }

    void diff(int value, boost::strict_lock<count_test>& strict_l)
    {
    count -= value;
    }
    void diff(int value) {
    boost::lock_guard<count_test> lock_g(*this);
    count -= value;
    }

    可以看出,在以上代码中,我们重载了 count_test 类的成员函数,使其都可以强制传入一个 boost::strict_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
    void test7()
    {
    const int N = 5;
    const int basic_value = 10'000;
    const int adding = 100;
    const int diffing = 200;
    count_test account(basic_value);

    boost::thread_group thrd_g;

    for (int i = 0; i < N; ++i)
    {
    thrd_g.add_thread(new boost::thread([&account](int add, int diff) -> void {
    boost::strict_lock<count_test> guard(account); // declare a externally strict_lock
    // bellow use forwarding call to change the filed of guard to lock the function
    account.add(add, guard); // force to use externally lock
    account.diff(diff, guard); // force to use externally lock
    }, adding, diffing));
    }

    thrd_g.join_all();

    std::cout << "account: " << account.get_count_value() << std::endl;
    }

    以上改写并重载的函数相当 安全 且 高效 。此时,对于单个账户的操作可以直接调用 内部锁定 版本。且,对于复杂事务,可以使用外部锁定,(如,以上代码中的锁定,在跳出函数之后,其对象仍是持有该锁的,所以不会出现其他对象竞争到这个锁)可以 精确的控制锁定顺序,防止死锁 。(引用传入 并不会导致在其传入的作用域结束后被销毁,即,可以在其所存在的 顶层作用域 之内保持锁定效果,扩展了锁的生命周期)

    这样使用的 外部锁 ,将锁的生命周期从单个函数扩展到整个事务操作的范围

    因为,对于设计上锁与解锁,很大一部分情况下都是忘记解锁,且,使用 boost::strict_lock 允许对最常见的错误来源进行编译时检查,对不太常见的问题进行运行时检查

    在此时的外部锁定中为了检查是否持有锁,则可以在强制外部锁定的方法中使用 boost::strict_lock 对象的 owns_lock(this) 函数。如:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    void add(int value, boost::strict_lock<count_test>& strict_l) // externally lock
    {
    // not need to write an internally lock
    if (!strict_l.owns_lock(this))
    throw "Locking Error: Wrong Object Locked";
    count += value;
    }

    void diff(int value, boost::strict_lock<count_test>& strict_l)
    {
    if (!strict_l.owns_lock(this))
    throw "Locking Error: Wrong Object Locked";
    count -= value;
    }

    遇到不包含锁的类型直接抛出运行时错误。

  • 改进外部锁定

    假设 BankAccount 类,不使用自己的锁定,并且只有一个线程中性的实现。

    假设有一个 AccountManager 类,其持有和操作 BankAccount 对象。

    假设,根据以上设计,AccountManager 在访问器 BankAccount 成员时必须保持锁定状态。

    此时需要使用一个 boost::externally_locked 对象模板来控制 BankAccount 的访问

    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
    60
    61
    62
    class BankAccount
    {
    private:
    double balence;

    public:
    BankAccount() { this->balence = 0.0; }

    public:
    void Deposit(double amount)
    {
    this->balence += amount;
    }

    void Withdraw(double amount)
    {
    this->balence -= amount;
    }

    const double get_value() const { return this->balence; }
    };

    class AccountManager
    : public boost::basic_lockable_adapter<boost::mutex>
    {
    private:
    boost::externally_locked<BankAccount, AccountManager> checkingAcc;
    boost::externally_locked<BankAccount, AccountManager> savingAcc;

    public:
    AccountManager()
    : checkingAcc(*this), savingAcc(*this) {}

    public:
    inline void Checking2Saving(int amount, boost::strict_lock<AccountManager>& guard)
    {
    checkingAcc.get(guard).Withdraw(amount);
    savingAcc.get(guard).Deposit(amount);
    }
    inline void Checking2Saving(int amount)
    {
    boost::strict_lock<AccountManager> guard(*this);
    checkingAcc.get(guard).Withdraw(amount);
    savingAcc.get(guard).Deposit(amount);
    }
    inline void AMoreComplicatedChecking2Savings(int amount)
    {

    }

    double get_checking()
    {
    boost::strict_lock<AccountManager> guard(*this);
    return checkingAcc.get(guard).get_value();
    }

    double get_saving()
    {
    boost::strict_lock<AccountManager> guard(*this);
    return savingAcc.get(guard).get_value();
    }
    };

    其模式与之前相同,要访问由checkingAcc封装的BankAccount对象,需要调用 get 。为调用 get ,需要传递给它一个 boost::strict_lock 。不要持有提供过调用get获得的指针或引用。若这样,则需要确保在 boost::strict_lock 被销毁后不要使用这些内容。即,尽量不要给封装的对象起别名。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    void test8()
    {
    const int N = 5;
    const int amount = 10'000;
    boost::thread_group thrd_g;
    AccountManager am;

    for (int i = 0; i < N; ++i)
    {
    thrd_g.add_thread(new boost::thread([&am](int amt) -> void {
    boost::strict_lock<AccountManager> guard(am);
    am.Checking2Saving(amt, guard);
    }, amount));
    }

    thrd_g.join_all();

    std::cout << "Checking: " << am.get_checking() << std::endl;
    std::cout << "Saving: " << am.get_saving() << std::endl;
    }

    当然以上函数的循环中,可以直接调用 am.Checking2Saving(amt) 内部锁定版本。

    上述构造的使用例子中,checkingAcc 和 savingAcc 的声明清楚的表明了该变量受 AccountManager 上的锁保护。其次,该设计使得实际锁定 BankAccount 的情况下无法操纵这两个账户。

    同时,在代码逻辑中直接表明了多个对象是如何共享相同的锁的逻辑,即 externally_locked 是一种主动文档。明确的表明了设计意图。不需要维护多个同级的类型的不同的锁,及其所之间的顺序管理。将锁设计 由 隐式约定 变为 显示约束 ,提高了代码的可靠性与可维护性。

    通过 集中锁定 的方式,让所有的账户都共享同一个锁 AccountManager ,避免了分别单独使用 boost::strict_lock 在限定顺序的同步操作时会存在的死锁问题。
    且共享同一个锁的情况下可以极大的减少管理许多不同的互斥量的开销。

    当然,我们也可以看到,对于使用了 externally_locked 包装的成员对象的构造函数初始化方法被限制,只能由系统自动调用其默认构造函数进行初始化。所以需要在其所在的类(即,多对象的共享锁类)中编写一些关于这些被包装的对象的初始化接口。

    • 关于显式初始化的接口设计
      • 初始化方法 + 状态检查

        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
        class ProperlyInitializedBankAccount {
        private:
        double balance_;
        std::string account_id_;
        AccountType type_;
        bool initialized_ = false; // 跟踪初始化状态

        public:
        ProperlyInitializedBankAccount() = default; // 默认构造

        // 显式初始化方法
        void initialize(const std::string& id, double initial_balance, AccountType type) {
        if (initialized_) {
        throw std::runtime_error("Account already initialized");
        }

        account_id_ = id;
        balance_ = initial_balance;
        type_ = type;
        initialized_ = true;
        }

        // 所有业务方法检查初始化状态
        void deposit(double amount) {
        if (!initialized_) {
        throw std::runtime_error("Account not initialized");
        }
        balance_ += amount;
        }

        void withdraw(double amount) {
        if (!initialized_) {
        throw std::runtime_error("Account not initialized");
        }
        if (balance_ >= amount) {
        balance_ -= amount;
        } else {
        throw std::runtime_error("Insufficient funds");
        }
        }

        bool is_initialized() const { return initialized_; }
        const std::string& get_account_id() const {
        if (!initialized_) throw std::runtime_error("Account not initialized");
        return account_id_;
        }
        };
      • 使用共享锁类进行集中初始化

        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
        class AccountManager 
        : public boost::basic_lockable_adapter<boost::mutex> {
        private:
        struct AccountConfig {
        std::string id;
        double initial_balance;
        AccountType type;
        };

        boost::externally_locked<BankAccount, AccountManager> checking_account_;
        boost::externally_locked<BankAccount, AccountManager> savings_account_;
        bool initialized_ = false;

        public:
        AccountManager()
        : checking_account_(*this), savings_account_(*this) {}

        // 集中初始化方法
        void initialize_accounts(const AccountConfig& checking_config,
        const AccountConfig& savings_config,
        boost::strict_lock<AccountManager>& lock) {
        if (initialized_) {
        throw std::runtime_error("Accounts already initialized");
        }

        // 通过专门的初始化方法来设置账户状态
        initialize_bank_account(checking_account_.get(lock), checking_config);
        initialize_bank_account(savings_account_.get(lock), savings_config);

        initialized_ = true;
        }

        // 重载:内部锁定版本
        void initialize_accounts(const AccountConfig& checking_config,
        const AccountConfig& savings_config) {
        boost::strict_lock<AccountManager> lock(*this);
        initialize_accounts(checking_config, savings_config, lock);
        }

        // 业务方法检查初始化状态
        void transfer_to_savings(double amount, boost::strict_lock<AccountManager>& lock) {
        if (!initialized_) {
        throw std::runtime_error("Accounts not initialized");
        }

        checking_account_.get(lock).withdraw(amount);
        savings_account_.get(lock).deposit(amount);
        }

        private:
        static void initialize_bank_account(BankAccount& account, const AccountConfig& config) {
        // 假设 BankAccount 有初始化方法
        account.initialize(config.id, config.initial_balance, config.type);
        }
        };
      • 工厂模式 + 延迟初始化

        使用了 智能指针,可使用可变参数模板对构造函数进行兼容,而且该方法可以灵活更换对象,但是在使用对象前需要注意检查对象指针的合法性

        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
        class AccountFactory {
        public:
        static std::unique_ptr<BankAccount> create_account(
        const std::string& id, double balance, AccountType type) {

        auto account = std::make_unique<BankAccount>();
        account->initialize(id, balance, type);
        return account;
        }
        };

        class FlexibleAccountManager
        : public boost::basic_lockable_adapter<boost::mutex> {
        private:
        std::unique_ptr<BankAccount> checking_account_ptr_;
        std::unique_ptr<BankAccount> savings_account_ptr_;

        // 使用 externally_locked 包装 unique_ptr
        boost::externally_locked<std::unique_ptr<BankAccount>, FlexibleAccountManager>
        checking_account_;
        boost::externally_locked<std::unique_ptr<BankAccount>, FlexibleAccountManager>
        savings_account_;

        public:
        FlexibleAccountManager()
        : checking_account_(std::make_unique<BankAccount>(), *this)
        , savings_account_(std::make_unique<BankAccount>(), *this) {}

        // 灵活的初始化 - 可以随时更换账户对象
        void set_checking_account(std::unique_ptr<BankAccount> account,
        boost::strict_lock<FlexibleAccountManager>& lock) {
        checking_account_.get(lock) = std::move(account);
        }

        void set_savings_account(std::unique_ptr<BankAccount> account,
        boost::strict_lock<FlexibleAccountManager>& lock) {
        savings_account_.get(lock) = std::move(account);
        }

        // 使用账户前检查是否已设置
        void deposit_to_checking(double amount, boost::strict_lock<FlexibleAccountManager>& lock) {
        auto& account_ptr = checking_account_.get(lock);
        if (!account_ptr) {
        throw std::runtime_error("Checking account not set");
        }
        account_ptr->deposit(amount);
        }

        bool is_checking_account_set(boost::strict_lock<FlexibleAccountManager>& lock) const {
        return static_cast<bool>(checking_account_.get(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
        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
        class AccountManagerBuilder {
        private:
        struct AccountData {
        std::string id;
        double initial_balance = 0;
        AccountType type = AccountType::CHECKING;
        };

        AccountData checking_data_;
        AccountData savings_data_;

        public:
        AccountManagerBuilder& with_checking_account(const std::string& id, double balance) {
        checking_data_ = {id, balance, AccountType::CHECKING};
        return *this;
        }

        AccountManagerBuilder& with_savings_account(const std::string& id, double balance) {
        savings_data_ = {id, balance, AccountType::SAVINGS};
        return *this;
        }

        std::unique_ptr<AccountManager> build() {
        auto manager = std::make_unique<AccountManager>();

        // 初始化账户
        boost::strict_lock<AccountManager> lock(*manager);
        manager->initialize_checking_account(checking_data_.id, checking_data_.initial_balance, lock);
        manager->initialize_savings_account(savings_data_.id, savings_data_.initial_balance, lock);

        return manager;
        }
        };

        // 在 AccountManager 中添加专门的初始化方法
        class AccountManager : public boost::basic_lockable_adapter<boost::mutex> {
        // ... 其他成员 ...

        public:
        void initialize_checking_account(const std::string& id, double balance,
        boost::strict_lock<AccountManager>& lock) {
        checking_account_.get(lock).initialize(id, balance, AccountType::CHECKING);
        }

        void initialize_savings_account(const std::string& id, double balance,
        boost::strict_lock<AccountManager>& lock) {
        savings_account_.get(lock).initialize(id, balance, AccountType::SAVINGS);
        }
        };

        // 使用构建器
        void usage_example() {
        auto manager = AccountManagerBuilder()
        .with_checking_account("CHECK001", 1000.0)
        .with_savings_account("SAVE001", 5000.0)
        .build();

        // manager 现在已经完全初始化
        }
  • 允许其他严格锁

围绕函数执行

该库提供了一种在函数执行期间进行锁定的方法

boost::with_lock_guard<Lockable, Function, Args…>(Lockable, Function, Args…)

互斥锁概念

互斥锁对象有助于 防止数据竞争 ,并允许线程之间的数据进行 线程安全同步 。线程通过调用锁函数之一 获得 互斥对象的 所有权 ,并通过调用相应的解锁函数 放弃 所有权 。
Boost.Thread 提供具有独占所有权语义的 递归 和 非递归 互斥锁,以及 共享所有权(多读、单写) 互斥锁。
以下的概念中都有集成有 CPP类型萃取 进行类型分析,但在笔记中并不详述。命名都是 **is_**格式

  • 互斥量的关键设计点

    它协调的是不同线程对同一资源的访问,而不是跟踪哪个具体线程应该访问。所有权机制确保同一时间只有一个线程可以进入临界区,无论这个线程是谁。

  • Boost.Thread 支持锁对象的四个基本概念:

    • Lockable
    • TimedLockable
    • SharedLockable
    • UpgradeLockable

    每种互斥锁类型都实现以上概念中的一个或多个,各种锁类型也是如此。

  • BasicLockable 概念

    <boost/thread/lockable_concepts.hpp>

    此概念,对 独占所有权进行建模 。如果以下表达式格式良好并具有指定语义,则该类型满足 BasicLockable 要求。

    通过 lock() 或的所有权必须通过 unlock() 释放

    • obj.lock();

      通过该调用 获得 锁的所有权

      要求 如果互斥锁不是递归的,则调用线程不拥有互斥锁。(调用线程:当前正在执行该函数的线程)即,不能在同一线程中连续重复获取互斥锁。

      效果 当前线程阻塞,直到可以为当前线程获得所有权。即,阻塞结束后才可能获取互斥锁。

      同步 对同一对象执行先前的 unlock() 操作与此操作同步。即,线程获取的锁的所有权在使用后需要主动释放。

    • obj.unlock();

      通过该调用 释放 锁的所有权

      要求 当前线程拥有 obj 。

      同步 此操作与后续获得同一对象所有权的锁操作同步。

      效果 释放 当前线程对 obj 的 锁定

  • Lockable 概念

    若类型满足 Lockable 的要求,则其也 必须满足 BasicLockable 的要求,并且以下表达式形势良好且具有指定的语义。

    • obj.try_lock()

      通过该调用获得锁的所有权,且必须通过调用 unlock() 释放

      要求 若互斥锁不是递归的,则调用线程不拥有互斥锁。

      效果 尝试 为当前线程获取所有权而 不阻塞 。即,仅仅是立即判断是否可以获取锁,若可,则获得锁;若非,则不获取锁,同时不阻塞,继续执行可用下文。

      同步 若 try_lock() 返回 true ,则对同一对象先前的 unlock() 操作与此操作同步。

      注意 由于 unlock() 不与随后失败的 try_lock() 同步,因此可见性规则非常弱,以至于在获取失败后几乎无法了解状态,即使在没有虚假失败的情况下也是如此。

  • TimedLockable 概念

    TimedLockable 概念细化了 Lockable 概念,以添加在尝试获取锁时对超时的支持。

    如果类型满足 TimedLockable 的要求,则它必须满足 Lockable 的要求,并且以下表达形式良好且具有指定的语义。

    变量

    • obj 为互斥量类型的值
    • rel_time 表示 chrono::duration 的实例
    • abs_time 表示 chrono::time_point 的实例

    表达式

    • obj.try_lock_for(rel_time)

      要求 锁互斥锁不是递归的,则调用线程不拥有互斥锁。

      效果 尝试为当前线程获取所有权。 阻塞 ,直到可以 获取所有权 或 超过了指定等待的时间 。

      同步 若返回 true 则对同一对象先前的 unlock() 操作同步。

    • obj.try_lock_until(abs_time)

      要求 若互斥量不是递归的,则调用线程不拥有互斥锁。

      效果 尝试为当前线程获取所有权。 阻塞 ,直到可以 获取所有权 或 达到指定时间 。

      同步 若返回值为 true 则对同一对象先前的 unlock() 操作同步。

    • obj.timed_lock(rel_time)

    • obj.timed_lock(abs_time)

    通过以上四个表达式获得的锁,必须通过调用 unlock() 进行释放

  • SharedLockable 概念

    之前的 lock() unlock() 等方法都是 独占锁 写者锁
    以下的 *_shared() 方法都是 共享锁 读者锁

    SharedLockable 概念 是 TimedLockable 概念 的改进, 允许共享所有权 和 独占所有权 。是标准的 多读/单写 模型:最多只能有一个线程拥有独占所有权,如果任何线程拥有 独占所有权 ,则其他线程 不能拥有共享或独占所有权 。或者,许多线程可以拥有共享所有权。

    如果类型满足 SharedLockable 的要求,则其必须满足 TimedLockable 的要求,并且以下表达式格式良好且具有指定的语义。

    变量

    • obj 表示类型的值
    • rel_time 表示 chrono::duration 的实例
    • abs_time 表示 chrono::time_point 的实例

    表达式

    • obj.lock_shared()

      效果 当前 线程阻塞 ,直到可以为当前线程获得共享所有权。

      后置条件 当前线程拥有 obj 的共享所有权。

    • obj.try_lock_shared()

      效果 尝试在 不阻塞 的情况下为当前线程获取共享所有权。

      后置条件 如果调用返回 true ,则当前线程拥有 obj 的共享所有权。

    • obj.try_lock_shared_for(rel_time)

      效果 尝试为当前线程获取共享所有权。 阻塞 直到获得共享所有权,或者经过指定的时间。如果指定的时间已经过去,则表现为 try_lock_shared() 。

    • obj.try_lock_shared_until(abs_time)

      效果 尝试为当前线程获取共享所有权。 阻塞 直到获得共享所有权,或者达到指定的时刻。若指定的时刻已经过去,则表现为 try_lock_shared() 。

    • obj.unlock_shared()

      先决条件 当前线程拥有 obj 的共享所有权。

      效果 释放当前线程对 obj 的共享所有权。

      后置条件 当前线程不再拥有 obj 的共享所有权。

    • obj.timed_lock_shared(abs_time)

      效果 尝试为当前线程获取共享所有权。 阻塞 直到获得共享所有权,或达到指定的时刻。如果指定的时刻已经过去,则表现为 try_lock_shared() 。

    通过调用以上方法获取锁的所有权,必须通过 obj.unlock_shared() 进行释放。

  • UpgradeLockable 概念

    UpgradeLockable 概念 是对 SharedLockable 概念的改进,允许 可升级所有权 以及 共享所有权 和 独占所有权 。

    单个线程可以拥有 可升级所有权 ,同时 其他线程可以拥有 共享所有权 。

    可升级所有权线程,可以随时尝试将其所有权升级为 独占所有权 。若没有其他线程拥有共享所有权,则升级立即完成,此时必须通过调用 unlock() 来释放锁。

    若在其他线程拥有共享所有权是进行升级,则尝试将失败,并且该线程将被 阻塞 ,直到可以获取 独占所有权 。

    所有权可以被 降级 或 升级 。

    共享所有权 → 可升级所有权 → 独占所有权

    类型满足 UpgradeLockable 要求,则它满足 SharedLockable 要求,并且以下表达式格式良好且具有指定的语义。

    通过调用 lock_upgrade() 获取的锁所有权必须通过调用 unlock_upgrade() 来释放。如果通过调用 unlock_xxx_and_lock_yyy() 函数更改了所有权类型,则必须通过相应的所有权释放函数进行所有权释放。

    • obj.lock_upgrade()

      先决条件 调用线程不拥有互斥锁

      效果 当前线程 阻塞 ,直到可以为当前线程获得升级所有权。

    • obj.unlock_upgrade()

      先决条件 当前线程拥有 obj 的升级所有权。

      效果 释放当前线程对 obj 的升级所有权

      同步 此操作与后续获得同一对象所有权的锁操作同步。

条件变量

<boost/thread/condition_variable.hpp>

类 condition_variable 和 condition_variable_any 提供了一种机制,允许一个线程 等待 另一个线程通知某个特定条件已变为真。

一般用法是,一个线程锁定一个互斥量,然后在 condition_variable 或 condition_variable_any 的实例上调用 wait 。当线程从 等待中唤醒 时,它会检查相应的条件是否现在为真,若是,则继续。若非,则调用 wait() 继续等待。有两种返回值,bool cv_stat枚举量。

注意,lock被传递给wait,wait原子的将线程添加到等待条件变量的线程集合中,并解锁互斥锁。当线程被唤醒时,互斥锁将在调用wait返回之前再次被锁定。这允许其他线程获取互斥锁以更新共享数据,并确保与条件相关联的数据被正确同步。

同时,另一个线程将条件设置为 true ,然后在条件变量上调用 notify_one 或 notify_all 以分别唤醒(通知)一个等待线程或所有等待线程。

同步原语 wait 与 线程操作 yeild 的区别在于:
yeild 是由线程自身让出时间片给其他线程。是一种 就绪状态 。仍消耗CPU周期。
wait 是为了等待特定的同步而主动进入阻塞状态。是一种 等待/阻塞状态 。CPU周期使用为零。

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
60
61
class ReadWriteCondition
{
private:
static boost::shared_mutex shrd_mtx;
static boost::condition_variable_any cv_any;
static int version_last;
private:
static std::string msg;
public:
std::string name;
public:
ReadWriteCondition(const std::string& str)
: name(str) { }

ReadWriteCondition(const ReadWriteCondition&) = delete;
ReadWriteCondition& operator=(const ReadWriteCondition&) = delete;
public:
std::string get_name() const { return this->name; }
void write(const std::string& str)
{
{
boost::unique_lock<boost::shared_mutex> uniq_l(this->shrd_mtx);
msg = str;
++version_last;
std::cout << std::endl << this->name << " Is Writing(VERSION " << version_last << "):\n\t" << str << std::endl;

boost::this_thread::sleep_for(boost::chrono::milliseconds(735));
}

cv_any.notify_all();
}

void read()
{
boost::shared_lock<boost::shared_mutex> shrd_l(shrd_mtx);
int current_version = version_last;

auto check_clock_start = boost::chrono::high_resolution_clock::now();
cv_any.wait_for(shrd_l, boost::chrono::seconds(5),
[this, current_version]() -> bool {
return version_last != current_version;
}
);
auto check_clock_end = boost::chrono::high_resolution_clock::now();

std::cout << this->name << " Is Reading(VERSION " << version_last << "):\n\t" << msg;
boost::chrono::duration<double> check = check_clock_end - check_clock_start;
if (check > boost::chrono::seconds(5))
{
std::cout << "\n\t\tTIME OUT\t" << check.count() << "s\tNO MSG HAS WROTEN.\tHAS NO NEW MSG.";
}
std::cout << std::endl;

boost::this_thread::sleep_for(boost::chrono::milliseconds(125));
}
};
boost::shared_mutex ReadWriteCondition::shrd_mtx;
boost::condition_variable_any ReadWriteCondition::cv_any;
std::string ReadWriteCondition::msg = "A SIMPLE MSG.";
int ReadWriteCondition::version_last = 1;

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
void test2()
{
const int W = 3;
const int R = 5;
const int Nw = 5;
const int Nr = 11;

boost::thread_group thrds;

std::vector<std::unique_ptr<ReadWriteCondition>> writers;
std::vector<std::unique_ptr<ReadWriteCondition>> readers;

for (int i = 0; i < W; ++i)
{
writers.emplace_back(std::make_unique<ReadWriteCondition>(std::string("WRITER_") + std::to_string(i)));
}
for (int i = 0; i < R; ++i)
{
readers.emplace_back(std::make_unique<ReadWriteCondition>(std::string("READER_") + std::to_string(i)));
}

for (auto& writer : writers)
{
thrds.add_thread(new boost::thread([&writer, &Nw]() -> void {
for (int i = 0; i < Nw; ++i)
{
writer->write(std::string(writer->get_name() + std::string(" last wrote this changed this MSG.")));
}
}));
}
for (auto& reader : readers)
{
thrds.add_thread(new boost::thread([&reader, &Nr]() -> void {
for (int i = 0; i < Nr; ++i)
{
reader->read();
}
}));
}

thrds.join_all();

}

条件变量的同步原语 wait 中可以传入一个返回值为 bool 的谓词。
注意,在更新共享数据之前,会锁定一个互斥锁,但互斥锁不必再调用 notify_one 时保持锁定。

  • condition_variable

    • notify_one()

      效果 如果有任何线程当前在调用 wait 或 timed_wait 时被 阻塞 在 该类实例 上,则解除阻塞其中一个线程。

    • notify_all()

      效果 如果有任何线程当前在调用 wait 或 timed_wait 时被 阻塞 在 该类实例 上,则解除所有这些线程。

    • wait(boost::uniq_lockboost::mutex& lock)

      先决条件 lock 必须由当前线程锁定,并且或者当前没有其他线程正在等待 该类实例 ,或者在当前等待 该类实例 的所有线程中,对 wait 或 timed_wait 的调用中提供的 lock 对象执行 mutex() 成员函数将返回与此 wait 调用中 lock→mutex() 相同的值。

      效果 原子性的调用 lock_unlock() 并 阻塞当前线程 。当调用 this→notify_one() 或 this→notify_all() 通知时,或 虚假唤醒 时,线程将被 解除阻塞 。当线程被解除阻塞,在 wait 调用返回 之前 ,通过调用 lock.lock() 重新获取锁。如果函数因异常退出,也会通过调用 lock.lock() 来重新获取锁。

      后置条件 lock必须由当前线程锁定。

    • wait(boost::unique_lockboost::mutex& lock, predicate_type pred)

      效果

      1
      2
      3
      4
      while(!pred()
      {
      wait(lock);
      }
  • condition_variable_any

    其操作与 condition_variable 相同,只是更加泛用。可以用于其他锁类型(不止有 boost::mutex boost::unique_lock) 。

  • 非成员函数 notify_all_at_thread_exit(condition_variable& cond, unique_lock lk)

    要求 调用线程 锁定了 lk,并且没有其他线程在等待 cond,或者对于所有并发等待的线程提供的每个锁参数,lk.mutex() 返回相同的值。

    效果 将与 lk 关联的锁的所有权 转移到内部存储 ,并计划在当前线程退出时通知cond,当前线程的所有线程存储持续时间的对象已被销毁。此时的通知应如同。

    1
    2
    lk.unlock();
    cond.notify_all();

单次初始化

<boost/thread/once.hpp>

boost::call_once 提供了一种机制,用于确保初始化例程只运行一次,而不会发生数据竞争或死锁。

boost::call_once(once_flag& flag, Function& f, ArgTypes&&… args)

要求 Function和每个ArgTypes都是 可移动构造的 ,并且 invoke(decay_copy(boost::forward(f)), decay_copy(boost::forward(args))…)应该格式良好。

效果 对同一个 once_flag 对象调用 call_once 是串行化的。如果在同一个once_flag 对象上,之前并没有有效的 call_once 调用,则会像调用invoke(decay_copy(boost::forward<Function>(f)), decay_copy(boost::forward<ArgTypes>(args))...) 一样调用参数 func,并且当且仅当 invoke(decay_copy(boost::forward<Function>(f)), decay_copy(boost::forward<ArgTypes>(args))...) 返回且没有抛出异常时,call_once 的调用才生效。如果抛出异常,则该异常会传播给调用者。如果之前在同一个 once_flag 对象上存在有效的 call_once 调用,则 call_once 会返回而不调用 func。

屏障(barrier)

<boost/thread/barrier.hpp>

屏障是一个简单的概念,也被称为 汇合点 ,它是 多个线程之间的同步点 。

屏障配置为 特定数量的 线程 ,并且当线程到达屏障时,它们必须等待直到所有的线程都到达。一旦最后一个线程到达屏障,所有等待线程都可以继续,并且屏障会被 重置 。

boost::barrier 的实例 不可复制或移动

  • 构造函数 barrier(unsigned int count)

    效果 构造一个用于 count 个线程的屏障

  • 构造函数 barrier(unsigned int count, F&& completion)

    要求 完成函数调用 completion() 的结果类型是 void 或 unsigned int 。

    效果 构造一个用于 count 个线程和一个完成函数 completion 的屏障。

  • 析构函数 ~barrier()

    先决条件 没有线程在 *this 上等待。

    效果 销毁*this

  • bool wait()

    效果 阻塞 ,直到 count 个线程在 *this 上调用 wait 或 count_down_and_wait 。当第 count 个线程调用 wait 时,屏障会被 重置 ,并且所有等待线程都会被 解除阻塞 。

    重置取决于屏障是否使用 完成函数构造 。如果没有完成函数或者完成函数的结果为 void ,则重置包括恢复原始计数。否则,重置包括分配完成函数的结果(必须不为0)。

    返回值 对于每批等待线程中恰好的(就是最后一个wait的线程,直接导致屏障重置的线程)一个线程为 true ,否则为 false 。

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    void barray_funct_void_test()
    {
    std::cout << "Thread Over.\n";
    }
    void test1()
    {
    const int N = 5;
    boost::barrier bary(3, barray_funct_void_test);
    boost::thread_group thrds;

    for (int i = 0; i < N; ++i)
    {
    thrds.add_thread(new boost::thread([&bary, i]() -> void {
    bary.wait();
    std::cout << "the " << i << " thread" << std::endl;
    }));
    }

    thrds.join_all();
    }

    在上述用例中, barrier构造函数传入的 count 为 3,而创建了 N=5 个线程,在进入各个线程后直接使用 bary.wait() 进入barrier锁定,根据线程的启动顺序,可见,仅仅会(极大概率)输出 0,1,2 三个线程分配的 i 值。因为是这三个线程最先开始。这三个线程进行了同步。

    当然,其中由于 N=5 count=3 最后只剩下 2 个线程,程序一直处于等待中。( 屏障数 与 线程数 不匹配 时,会导致 死锁 )

    wait 返回值规律:每批到达屏障的线程中, 恰好有一个线程 会受到 true 其他收到 false

    屏障的核心价值在于:
    同步点 确保多个线程在特定点同步
    阶段控制 协调多阶段并行算法的执行
    数据一致性 在关键操作前确保所有线程就绪

    屏障重置的三种情况

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    // 情况1:无完成函数 - 重置为原始计数
    boost::barrier barrier1(4); // 总是重置为4

    // 情况2:有完成函数,返回void - 重置为原始计数
    boost::barrier barrier2(4, []() {
    std::cout << "Barrier reached!" << std::endl;
    }); // 总是重置为4

    // 情况3:有完成函数,返回unsigned int - 重置为返回值
    boost::barrier barrier3(4, []() -> unsigned int {
    static int call_count = 0;
    ++call_count;
    return (call_count % 2 == 0) ? 4 : 2; // 动态改变计数
    });

    其中,返回为 unsigned int 的完成函数,可以支持 动态的 调整并行策略。

  • void count_down_and_wait()

    效果 阻塞 ,直到 count 个线程在 *this 上调用 wait 或 count_down_and_wait 。当第 count 个线程调用 wait 时,屏障会被重置,并且所有等待线程都会被 解除阻塞 。

    重置取决于 屏障是否使用完成构造函数 。如果 没有完成函数 或 完成函数的结果是 void ,则重置包括恢复原始计数。否则,重置包括分配完成函数的结果(必须不为0)

    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

    unsigned int barray_funct_uint_completion_test()
    {
    static unsigned int call_count = 0;
    ++call_count;
    std::cout << "\t===> completion call <===\n";
    return 3;
    }
    void test2()
    {
    const int N = 9;
    boost::barrier bary(3, barray_funct_uint_completion_test);
    boost::thread_group thrds;

    for (int i = 0; i < N; ++i)
    {
    boost::this_thread::sleep_for(boost::chrono::milliseconds(333));
    thrds.add_thread(new boost::thread([&bary, i]() -> void {
    if (bary.wait())
    {
    std::cout << "\nsynchronolized Leader Thread: " << i << std::endl;
    }
    std::cout << "the " << i << " thread" << std::endl;
    }));
    }

    thrds.join_all();
    }

    count_down_and_wait() 功能与 wait() 的功能完全相同,而是只需要同步,而不用像 wait() 一样,不用关心哪个线程触发完成函数。(即,不关心 领导线程 。)

锁存器 latch

锁存器是一种 线程协调机制 ,允许一个或多个线程阻塞,直到一个或多个线程到达某个点。

latch

latch 维护一个 内部计数器 ,该计数器在 创建latch时初始化 。一个或多个线程可能会 阻塞等待 ,直到计数器递减到 0 。

latch 的实例不可复制或移动。

  • 构造函数 latch(std::size_t count)

    效果 构造一个 latch ,其中包含内部计数器的 初始值 。

    注意 计数器 可以为零

  • 析构函数 ~latch()

    先决条件 没有线程正在等待或调用 *this 上的 count_down 。

    效果 销毁 *this latch

  • wait()

    效果 阻塞调用线程,直到内部计数 达到零值 。然后,所有等待线程都被 解除阻塞 。

  • try_wait()

    返回值 如果内部计数为 0,则返回 true,否则返回 false。 不会阻塞调用线程 。

  • cv_status wait_for(const chrono_duration<Rep, Period>& rel_time)

    效果 阻塞调用线程 ,直到内部计数器达到零值或经过 rel_time 时间。如果 没有超时 ,所有等待线程都会被解除阻塞。

    即,等待一段时间内确定是否达到计数器耗尽。

    返回值 cv_status类型 若内部计数为0则 cv_status::no_timeout ,若经过 rel_time 时间,则为 cv_status::timeout 。

  • cv_status wait_until(const chrono::time_point<Clock, Duration>& abs_time)

    类似于之前所有的 until 成员定义。

  • count_down()

    要求 内部计数器非零。

    效果 将内部计数 -1 ,然后返回。若 计数器达到0 ,则将 释放 wait() 中阻塞的任何线程。

  • count_down_and_wait()

    结合调用了 count_down() 与 wait()

  • reset(size_t)

    要求 只有在当前没有其他线程在等待函数中时才能调用此函数。

    返回值 使用新的初始线程计数值 重置 latch

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

void test3()
{
const int N = 5;
boost::latch lach(N);

boost::thread_group thrds;

for (int i = 0; i < N; ++i)
{
thrds.add_thread(new boost::thread([&lach, i]() -> void {
lach.wait();

std::cout << "thread " << i << " unblocked.\n";
}));
}

for (int i = 0; i < N; ++i)
{
boost::this_thread::sleep_for(boost::chrono::milliseconds(500));
lach.count_down();
std::cout << i << "\tlatch countdown.\n\n";
}

thrds.join_all();
}

boost::barrier 线程间相互等待。可重复使用。
boost::latch 单向等待。一次性重复。(可在用尽后重置)

Futures

futures 库提供了一种处理同步 future 值的方法,无论这些值是由另一个线程生成,还是在单个线程上相应外部刺激,或按需生成。

boost::promise boost::futures boost::packaged_task 是对上述同步原语的更高级别的抽象。用于简化并发编程,特别是异步操作和线程间传递结果。

通过以下四个类模板来实现:

  • future
  • boost::shared_future 用于检索异步结果
  • boost::promise
  • boost::packaged_task 用于生成异步结果

future 的一个实例拥有 对结果的唯一引用 。

所有权可以在实例之间使用 移动构造函数 或 移动赋值运算符 进行转移,但最多只有一个实例拥有对 给定异步结果的引用 。当结果准备好时,它会通过 右值引用 从 boost::future::get() 返回,以便可以根据类型适当地 移动 或 复制 结果。

另一方面, boost::shared_future 的多个实例 可能引用相同的结果 。实例可以自由复制和分配,并且 boost::shared_future::get() 返回 const 引用,以便可以安全地多次调用 boost::shared_future::get() 。可以将 future 的实例移动到 boost::shared_future 的实例中,从而转移关联的异步结果的 多有权 ,但反之则不可。

boost::async 是一种运行异步任务的简单方法。调用 boost::aync 会返回一个 future ,该future将包含任务的结果。

可以单独使用future,也可以使用 boost::wait_for_any() 和 boost::wait_for_all() 函数之一等待。

  • 创建异步值

    可以使用 boost::promise 或 boost::packaged_task 设置 future 中的值。

    boost::packaged_task 是一个可调用对象,它包装一个函数或可调用对象。调用 packaged_task 时,它会 依次调用包含的函数 ,并使用返回值填充 future 。

    boost::promise 稍微低级一些:它只提供显式函数来将值或异常存储在关联的future中。因此,当值可能 来自多个可能的源 ,或者 单个操作可能产生多个值 时,可以使用promise。

    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
    void test5()
    {

    boost::packaged_task<int> pkt_t([]() -> int {
    boost::this_thread::sleep_for(boost::chrono::seconds(3));
    return 42;
    });

    auto fu = pkt_t.get_future();

    boost::thread thrd(boost::move(pkt_t));

    fu.wait();

    int value = fu.get();

    std::cout << "value = " << value << std::endl;
    }

    void test6()
    {
    boost::promise<int> pm;
    boost::unique_future<int> fu = pm.get_future();

    pm.set_value(42);

    std::cout << "value = " << fu.get() << std::endl;
    }
  • 等待回调和延迟 Future

    boost::promise 和 boost::packaged_task 都支持 等待回调 ,当线程在对 wait() 或 timed_wait() 的调用中 阻塞时 ,会调用该回调,该回调发生在等待来自 boost::promise 或 boost::packaged_task 的结果的future上时,该回调在执行等待的线程中。可以使用相应的 boost::promise 或 boost::package_task 上的 set_wait_callback() 成员函数来设置这些回调。

    这允许 延迟future ,其中直到某些线程需要结果时才实际计算结果。

    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
    int calculate_the_answer_to_life_the_universe_and_everything()
    {
    return 42;
    }

    void invoke_lazy_task(boost::packaged_task<int>& task)
    {
    try
    {
    task();
    }
    catch (boost::task_already_started&)
    {
    }
    }

    void test10()
    {
    boost::packaged_task<int> task(calculate_the_answer_to_life_the_universe_and_everything);
    task.set_wait_callback(invoke_lazy_task);
    boost::unique_future<int> f(task.get_future());

    std::cout << "value: " << f.get() << std::endl;
    }

    上述示例中, f.get() 的调用会回调 invoke_lazy_task ,该回调运行任务以设置该值。如果删除对 f.get() 的调用,则永远不会运行该任务。

  • 处理分离线程和线程特定变量

    分离线程给具有线程存储持续时间的对象带来了问题。如果使用除了 boost::thread::join() 的机制来等待 线程完成工作,如,等待future准备就绪,那么线程特定变量的析构函数 仍然会在等待线程恢复后运行 。方法是 确保在future 准备就绪之前 销毁具有线程存储持续时间的对象。

  • 异步执行

    boost::async 提供了一种简单的方式来运行异步任务,以利用可用的硬件并发性。

    调用 boost::async 会返回一个 boost::future ,该future将包含任务的结果。根据启动策略,任务可以在其自身的线程上异步运行,也可以在调用该future的wait() 或 get()成员函数的线程上同步运行。

    启动策略可以是 boost::launch::async(要求运行时创建一个异步线程) 或 boost::launch::deferred(表示只想函数调用延迟到稍后的时间,即惰性求值) 。此参数是可选的,若省略,函数将使用默认策略。

Future Reference

future类模板

  • 构造函数

    • 默认构造 future()

      效果 构造一个未初始化的 future

      后置条件 this→is_ready() return false ,this→get_state() return boost::future_state::uninitialized 。

    • 移动构造

      效果 构造一个 新的 future,并将与other关联的共享状态的 所有权转移 到 *this

      后置条件 this→get_state() 返回调用前 other→state() 的值。other→get_state() return boost::future_state::uninitialized 。如果 other 与共享状态 相关联 ,则该结果现在与 *this 相关联。other在执行后 不与任何共享状态相关联 。

  • 析构函数

    • ~future()

      效果 销毁 *this

  • get()

    效果 如果*this与共享状态关联,则等待结果准备就绪,如同调用 boost::future::wait() 一样,并检索结果。

    返回值 R&存储值的引用 &&右值引用 void无返回值。

    注意 get() 是一个中断点。

  • wait()

    效果 如果*this与共享状态关联,则 等待 直到结果准备就绪。如果在进入时结果 尚未准备就绪,并且结果 设置了等待回调 ,则在等待之前调用该回调。即,先回调再等待。

    后置条件 this→is_ready() return true 。this→get_state() return boost::future_state::ready

    注意 wait() 是个中断点。

  • wait_for(chrono::duration)

    效果 *this与共享状态关联,则等待直到结果准备就绪,或经过 指定的时间 。如果再进入时结果未准备好,并且结果设置了等待回调,则再等待之前会调用该回调。

    返回值 future_status::deferred ready timeout

  • wait_until(chrono::time_point)

    效果 *this与状态关联,则等待结果准备就绪,或者抵达 指定的时刻 。如果再进入时结果未准备好,并且结果设置了等待回调,则在等待之前会调用该回调。

  • valid()

    返回值 *this与共享状态关联,则为true否则为false

    备注 此函数的结果不稳定,即使该函数返回true或反之亦然,future也可能变为无效。

  • is_ready()

    返回值 如果*this与共享状态关联,并且该结果 已经准备好进行检索 ,则为true,否则false

    备注 此函数的结果不稳定,即使该函数返回true或反之亦然,future也可能变为未就绪。

  • has_value()

    返回值 如果*this与共享状态关联,并且该结果是 存储的值 ,则为true,否则false。

    备注 此函数的结果不稳定,即使该函数返回true或反之亦然,future也可能 丢失其值 。

  • has_exception()

    返回值 如果this与共享状态关联,并且该结果 是*存储的异常 ,则为true,否则false。

    备注 此函数的结果不稳定,即使该函数返回true或反之亦然,future也可能 丢失其异常 。

  • get_state()

    效果 确定与*this关联的共享状态的状态。

    返回值类型 boost::future_state

  • share()

    返回值 shared_future(boost::move(*this)) 即,可以让 unique_future类型 由此 变为 shared_future 。

    后置条件 this→valid() == false

shared_future 类模板

包含所有上述 future类模板 中的成员函数。

shared_future的 get() 可以调用多次(而非一次),可由多个线程获取(而非一次性),可以自由 复制 和 赋值 unique_future仅支持移动构造和移动赋值。

若需要在 多线程的环境 中使用,对同一个异步结果进行访问,则 shared_future 是唯一安全的选择,因为它是 线程安全的 。

promise 类模板

  • 构造函数

    • 默认构造函数 promise()

      效果 构造一个新的 boost::promise 且不关联任何结果。

    • 移动构造

      效果 构造一个新的 boost::promise 并将其与other关联的结果的所有权转移到*this,使other不再关联任何结果。

  • 析构函数

    效果 销毁this。如果有一个与this关联的结果,并且该结果 尚未准备就绪 ,则将该任务关联的任何future设置为 准备就绪 ,并将 boost::broken_promise 异常作为结果。

  • get_future

    效果 如果this没有与结果关联,则为新的共享状态分配存储空间并将其与this关联。返回一个与*this关联的 结果相关联 的future。

    效果- 如果定义了 BOOST_THREAD_PROVIDES_PROMISE_LAZY 并且 *this 没有与结果关联,则为新的共享状态分配存储空间并将其与 *this 关联。

    • 将值 r 存储在与 *this 关联的共享状态中。唤醒任何被阻塞并等待异步结果的线程。后置条件所有等待共享状态的 future 都已准备就绪,并且这些 future的 boost::future::has_value() 或 boost::shared_future::has_value() 应该返回 true。
  • set_value_at_thread_exit()

    效果 将值 r 存储在共享状态中,但不会立即使该状态变为就绪状态。 安排该状态在当前线程退出时变为就绪状态,此时与当前线程关联的所有线程存储持续时间的对象的析构函数都已执行完毕。

    后置条件 与 *this 关联的结果被设置为 deferred (延迟的)。

  • notify_deferred

    效果 任何 阻塞 等待异步结果的线程都会被唤醒。即,ready状态。

packaged_task 类模板

  • 重载了void operator() 可以直接调用传入的函数对象,
  • reset() 重置 packaged_task 的状态,以便于再次调用。
  • set_wait_callback()

非成员函数 async()

传入一个函数,及其参数。返回一个future类型。