C++ in Chromium 101 - Codelab 编程开始 bind 多线程 回调
实现回调三步走:
a. 声明一个函数变量,有两种once和repeat:
base::OnceCallback<int(std::string, double)> func1; base::RepeatingCallback<int(std::string, double)> func2;
b. 给变量初始化:base::BindOnce()
or base::BindRepeating()
void MyFunction(int32 a, double b); base::OnceCallback<void(double)> my_callback1 = base::BindOnce(&MyFunction, 10); base::RepeatingCallback<void(double)> my_callback2 = base::BindRepeating(&MyFunction, 10);
c. 执行回调函数变量
对于once类型的,需要通过c++ move语义,只执行一次后变量会被清空。repeat没有限制。
std::move(my_callback1).Run(3.5); my_callback2.Run(3.5);
1,这个函数接收 函数变量。并执行这个回调函数。
void MyFunction1(base::OnceCallback<int(int32, double)> my_callback) { // OnceCallback int result1 = std::move(my_callback).Run(10, 1.0); // After running a OnceCallback, it's consumed and nulled out. DCHECK(!my_callback) ... }
2,这是个回调函数 实现部分:
void MyFunction(int32 a, double b){ xxxx }
MyFunction回调函数通过bind创建了回调函数,赋值给了my_callback1这个回调函数变量。并绑定了第一个参数为10。
base::OnceCallback<void(double)> my_callback1 = base::BindOnce(&MyFunction, 10); //这个10相当于第一个参数是10,第二个参数run时再指定:如std::move(my_callback1).Run(3.5);
3, 将回调函数my_callback1传给了MyFunction1。 MyFunction1拥有了回调函数。什么时候回调函数执行取决于合适调用 my_callback1 的Run方法。这里是传递后就被调用。也可以等时机去调用。
MyFunction1(my_callback1)
ok
更多可以参考:
Chromium多线程通信的Closure机制分析:罗升阳的bind介绍
https://blog.csdn.net/luoshengyang/article/details/46747797
chromium log 调用时不配置的话,默认会输出到可执行文件相同目录下的 debug.log 中。
在实验101时,会导致chrome代码重新编译。小心
如果自己新添加目录在src下,比如 mytest
需要在src目录的build.gn里面
group("gn_all") {
testonly = true
deps = [
添加上 "//mytest:mygroup",
并且在mytest目录下的BUILD.gn里面写上:
group("mygroup") { testonly = true deps = [ ":myexe", ] } executable("myexe") { sources = [ "//mytest/cpp101/hello_world.cc" ] deps = [ "//base" ] }
就可以生成gn和编译( --ide=vs 生成visual studio sln文件;--args生成args.gn在out\cpp101下,与直接写这个文件效果一样)
:
cd /d Z:\chromium\src\out\cpp101 hello_chromium.exe
这个随源码发放:/src/codelabs/cpp101/
在线可看:https://chromium.googlesource.com/chromium/src/+/HEAD/codelabs/cpp101/codelab.md
C++ in Chromium 101 - Codelab
This tutorial will guide you through the creation of various example C++ applications, highlighting important Chromium C++ concepts. This tutorial assumes robust knowledge of C++ (the language) but does not assume you know how to write an application specific to Chromium‘s style and architecture. This tutorial does assume that you know how to check files out of Chromium’s repository.
As always, consider the following resources as of primary importance:
- Coding Style
- Callback<> and Bind()
- Threading and Tasks in Chrome
- Intro to Mojo & Services
- Important Abstractions and Data Structures (badly needs updating)
This tutorial does not assume you have read any of the above, though you should feel free to peruse them when necessary. This tutorial will cover information across all of those guides.
Exercise solutions are available in the codelabs/cpp101/ directory of the Chromium source code. Build all of the example solutions with autoninja -C out/Default codelabs
. You are encouraged to create a new base/cpp101/
directory locally if you want to try implementing these exercises yourself.
Exercise 0: “Hello World!”
This exercise demonstrates the use of the ninja build system to build a simple C++ binary and demonstrates how typical C++ builds are organized within Chromium.
Create a new target in base/BUILD.gn
for a new executable named codelab_hello_world
. Then write the classic “Hello, world!” program in C++. You should be able to build it with autoninja -C out/Default codelab_hello_world
and execute it directly by finding the binary within out/Default
.
Sample execution:
$ cd /path/to/chromium/src $ gclient runhooks $ autoninja -C out/Default codelab_hello_world $ out/Default/codelab_hello_world Hello, world! [0923/185218.645640:INFO:hello_world.cc(27)] Hello, world!
More information
Git Tips and Git Cookbook
Part 1: Using command-line arguments
We will augment our codelab_hello_world
binary to parse command-line flags and use those values to print messages to the user.
Command-line arguments within Chromium are processed by the CommandLine::Init()
function, which takes command line flags from the argc and argv (argument count & vector) variables of the main() method. A typical invocation of CommandLine::Init()
looks like the following:
int main(int argc, char** argv) { CommandLine::Init(argc, argv); // Main program execution ... return 0; }
Flags are not explicitly defined in Chromium. Instead, we use GetSwitchValueASCII()
and friends to retrieve values passed in.
Important include files
#include "base/command_line.h" #include "base/logging.h"
Exercise 1: Using command-line arguments
Change codelab_hello_world
to take a --greeting
and a --name
switch. The greeting, if not specified, should default to “Hello”, and the name, if not specified, should default to “World”.
Part 2: Callbacks and Bind
C++, unlike other languages such as Python, Javascript, or Lisp, has only rudimentary support for callbacks and no support for partial application. However, Chromium has the base::OnceCallback<Sig>
and base::RepeatingCallback<Sig>
class, whose instances can be freely passed around, returned, and generally be treated as first-class values. base::OnceCallback is the move-only, single-call variant, and base::RepeatingCallback is the copyable, multiple-call variant.
The Sig
template parameter is a function signature type:
// The type of a callback that: // - Can run only once. // - Is move-only and non-copyable. // - Takes no arguments and does not return anything. // base::OnceClosure is an alias of this type. base::OnceCallback<void()> // The type of a callback that: // - Can run more than once. // - Is copyable. // - Takes no arguments and does not return anything. // base::RepeatingClosure is an alias of this type. base::RepeatingCallback<void()> // The types of a callback that takes two arguments (a string and a double) // and returns an int. base::OnceCallback<int(std::string, double)> base::RepeatingCallback<int(std::string, double)>
Callbacks are executed by invoking the Run()
member function. base::OnceCallback needs to be rvalue to run.
void MyFunction1(base::OnceCallback<int(std::string, double)> my_callback) { // OnceCallback int result1 = std::move(my_callback).Run("my string 1", 1.0); // After running a OnceCallback, it's consumed and nulled out. DCHECK(!my_callback); ... } void MyFunction2(base::RepeatingCallback<int(std::string, double)> my_callback) { int result1 = my_callback.Run("my string 1", 1.0); // Run() can be called as many times as you wish for RepeatingCallback. int result2 = my_callback.Run("my string 2", 2); ...
Callbacks are constructed using the base::BindOnce()
or base::BindRepeating()
function, which handles partial application:
// Declare a function. void MyFunction(int32 a, double b); base::OnceCallback<void(double)> my_callback1 = base::BindOnce(&MyFunction, 10); base::RepeatingCallback<void(double)> my_callback2 = base::BindRepeating(&MyFunction, 10); // Equivalent to: // // MyFunction(10, 3.5); // std::move(my_callback1).Run(3.5); my_callback2.Run(3.5);
base::BindOnce()
and base::BindRepeating()
can do a lot more, including binding class member functions and binding additional arguments to an existing base::OnceCallback
or base::RepeatingCallback
. See docs/callback.md for details.
Important Include Files
#include "base/bind.h" #include "base/callback.h"
More Information
Exercise 2: Fibonacci closures
Implement a function that returns a callback that takes no arguments and returns successive Fibonacci numbers. That is, a function that can be used like this:
base::RepeatingCallback<int()> fibonacci_closure = MakeFibonacciClosure(); LOG(INFO) << fibonacci_closure.Run(); // Prints "1" LOG(INFO) << fibonacci_closure.Run(); // Prints "1" LOG(INFO) << fibonacci_closure.Run(); // Prints "2" ...
Each returned Fibonacci callback should be independent; running one callback shouldn't affect the result of running another callback. Write a fibonacci
executable that takes an integer argument n
and uses your function to print out the first n
Fibonacci numbers.
(This exercise was inspired by this Go exercise: Function closures.)
Part 3: Threads and task runners
Chromium has a number of abstractions for sequencing and threading. Threading and Tasks in Chrome is a must-read and go-to reference for anything related to tasks, thread pools, task runners, and more.
Sequenced execution (on virtual threads) is strongly preferred to single-threaded execution (on physical threads). Chromium's abstraction for asynchronously running posted tasks is base::TaskRunner
. Task runners allow you to write code that posts tasks without depending on what exactly will run those tasks.
base::SequencedTaskRunner
(which extends base::TaskRunner
) is a commonly used abstraction which handles running tasks (which are instances of base::OnceClosure
) in sequential order. These tasks are not guaranteed to run on the same thread. The preferred way of posting to the current (virtual) thread is base::SequencedTaskRunnerHandle::Get()
.
A task that can run on any thread and doesn’t have ordering or mutual exclusion requirements with other tasks should be posted using one of the base::ThreadPool::PostTask()
functions.
There are a number of ways to post tasks to a thread pool or task runner.
PostTask()
PostDelayedTask()
if you want to add a delay.PostTaskAndReply()
lets you post a task which will post a task back to your current thread when its done.PostTaskAndReplyWithResult()
to automatically pass the return value of the first call as argument to the second call.
Normally you wouldn‘t have to worry about setting up a threading environment and keeping it running, since that is automatically done by Chromium’s thread classes. However, since the main thread doesn‘t automatically start off with TaskEnvironment
, there’s a bit of extra setup involved. The following setup code should be enough to create the necessary TaskEnvironment. Include testonly=true
flag in the BUILD.gn file, along with "//base/test:test_support"
set as a dependency.
Important header files
#include "base/test/task_environment.h" #include "base/test/test_timeouts.h" #include "base/at_exit.h" #include "base/threading/sequenced_task_runner_handle.h" #include "base/time/time.h" #include "base/command_line.h"
Setup code:
int main(int argc, char* argv[]) { base::AtExitManager exit_manager; base::CommandLine::Init(argc, argv); TestTimeouts::Initialize(); base::test::TaskEnvironment task_environment{ base::test::TaskEnvironment::TimeSource::SYSTEM_TIME}; // The rest of your code will go here.
Exercise 3a: Sleep
Implement the Unix command-line utility sleep
using only a base::SequencedTaskRunnerHandle
(i.e., without using the sleep
function or base::PlatformThread::Sleep
). Hint: You will need to use base::RunLoop
to prevent the main function from exiting prematurely.
Exercise 3b: Integer factorization
Take the given (slow) function to find a non-trivial factor of a given integer:
absl::optional<int> FindNonTrivialFactor(int n) { // Really naive algorithm. for (int i = 2; i < n; ++i) { if (n % i == 0) { return i; } } return absl::nullopt; }
Write a command-line utility factor
that takes a number, posts a task to the background using FindNonTrivialFactor
, and prints a status update every second as long as the factoring task is executing.
More information
Part 4: Mojo
Mojo is Chromium's abstraction of IPC. Mojo allows for developers to easily connect interface clients and implementations across arbitrary intra- and inter-process boundaries. See the Intro to Mojo and Services guide to get started.
Exercise 4: Building a simple out-of-process service
See the building a simple out-of-process service tutorial on using Mojo to define, hook up, and launch an out-of-process service.
代码位于chromium\src\codelabs\cpp101\
mojo.cc 是客户端调用程序
math_service->Divide(divisor, dividend, base::BindOnce( [](base::OnceClosure quit, int32_t quotient) { LOG(INFO) << "Quotient: " << quotient; std::move(quit).Run(); }, run_loop.QuitClosure()));
这个Divide 接口原型是
void Divide(int32_t dividend, int32_t divisor, DivideCallback callback) override;
我们看到第三个参数赋值为:
base::BindOnce( [](base::OnceClosure quit, int32_t quotient) { LOG(INFO) << "Quotient: " << quotient; std::move(quit).Run(); }, run_loop.QuitClosure())
base::BindOnce 将创建一个 函数指针变量。 这个函数指针指向一个 lamba 函数实现(红色部分),并且第一个参数绑定成:run_loop.QuitClosure()。
服务端实现:
void MathService::Divide(int32_t dividend, int32_t divisor, DivideCallback callback) { // Respond with the quotient! std::move(callback).Run(dividend / divisor); }
接收到 base::BindOnce 创建的 回调函数。
调用 Run 执行它。执行时会调用上面的 lamba函数,第一个参数传入 run_loop.QuitClosure(),第二个参数是 dividend / divisor。
More Information
Mojo C++ Bindings API Docs 里面放有大多数文档
Mojo & Services
- Intro to Mojo & Services - Quick introduction to Mojo and services in Chromium, with examples
- Mojo API Reference - Detailed reference documentation for all things Mojo
- Service Development Guidelines - Guidelines for service development in the Chromium tree
- Servicifying Chromium Features - General advice for integrating new and existing subsystems into Chromium as services
- Converting Legacy IPC to Mojo - Tips and common patterns for practical IPC conversion work
- Mojo “Style” Guide - Recommendations for best practices from Mojo and IPC reviewers
- D-Bus Mojo Connection Service - A service in Chrome to bootstrap CrOS services' Mojo connection.
Callback<> and Bind()[TOC] IntroductionThe templated Partial application is the process of binding a subset of a function's arguments to produce another function that takes fewer arguments. This can be used to pass around a unit of delayed execution, much like lexical closures are used in other languages. For example, it is used in Chromium code to schedule tasks on different MessageLoops. A callback with no unbound input parameters ( OnceCallback<> And RepeatingCallback<>
The legacy
Memory Management And PassingPass
When you pass a Quick reference for basic stuffBinding A Bare Function
Binding A Captureless Lambda
Binding A Capturing Lambda (In Tests)When writing tests, it is often useful to capture arguments that need to be modified in a callback.
Binding A Class MethodThe first argument to bind is the member function to call, the second is the object on which to call it.
By default the object must support RefCounted or you will get a compiler error. If you're passing between threads, be sure it's RefCountedThreadSafe! See "Advanced binding of member functions" below if you don't want to use reference counting. Running A CallbackCallbacks can be run with their
RepeatingCallbacks can be run more than once (they don't get deleted or marked when run). However, this precludes using
If running a callback could result in its own destruction (e.g., if the callback recipient deletes the object the callback is a member of), the callback should be moved before it can be safely invoked. (Note that this is only an issue for RepeatingCallbacks, because a OnceCallback always has to be moved for execution.)
Creating a Callback That Does NothingSometimes you need a callback that does nothing when run (e.g. test code that doesn't care to be notified about certain types of events). It may be tempting to pass a default-constructed callback of the right type:
Default-constructed callbacks are null, and thus cannot be Run(). Instead, use
Implementation-wise,
Passing Unbound Input ParametersUnbound parameters are specified at the time a callback is
Passing Bound Input ParametersBound parameters are specified when you create the callback as arguments to
A callback with no unbound input parameters (
When calling member functions, bound parameters just go after the object pointer.
Partial Binding Of ParametersYou can specify some parameters when you create the callback, and specify the rest when you execute the callback. When calling a function bound parameters are first, followed by unbound parameters.
This technique is known as partial application. It should be used in lieu of creating an adapter class that holds the bound arguments. Notice also that the Avoiding Copies With Callback ParametersA parameter of
Arguments bound with In contrast, arguments bound with DANGER: A Avoid using
Quick reference for advanced bindingBinding A Class Method With Weak PointersIf
The callback will not be run if the object has already been destroyed. Note that class method callbacks bound to To use
If Binding A Class Method With Manual Lifetime Management
This disables all lifetime management on the object. You're responsible for making sure the object is alive at the time of the call. You break it, you own it! Binding A Class Method And Having The Callback Own The Class
The object will be deleted when the callback is destroyed, even if it's not run (like if you post a task during shutdown). Potentially useful for "fire and forget" cases. Smart pointers (e.g.
Ignoring Return ValuesSometimes you want to call a function that returns a value in a callback that doesn't expect a return value.
Quick reference for binding parameters to Bind()Bound parameters are specified as arguments to Passing Parameters Owned By The Callback
The parameter will be deleted when the callback is destroyed, even if it's not run (like if you post a task during shutdown). Passing Parameters As A unique_ptr
Ownership of the parameter will be with the callback until the callback is run, and then ownership is passed to the callback function. This means the callback can only be run once. If the callback is never run, it will delete the object when it's destroyed. Passing Parameters As A scoped_refptr
This should "just work." The closure will take a reference as long as it is alive, and another reference will be taken for the called function.
Passing Parameters By ReferenceReferences are copied unless
Normally parameters are copied in the closure. DANGER: Implementation notesWhere Is This Design From:The design of Customizing the behaviorThere are several injection points that controls binding behavior from outside of its implementation.
If
How The Implementation Works:There are three main components to the system:
The Callback classes represent a generic function pointer. Internally, it stores a refcounted piece of state that represents the target function and all its bound parameters. The
To
The By default To change this behavior, we introduce a set of argument wrappers (e.g., These types are passed to the
Missing Functionality
If you are thinking of forward declaring
Partial application
Jump to navigationJump to search
In computer science, partial application (or partial function application) refers to the process of fixing a number of arguments to a function, producing another function of smaller arity. Given a function {\displaystyle f\colon (X\times Y\times Z)\to N} ContentsMotivation[edit]Intuitively, partial function application says "if you fix the first arguments of the function, you get a function of the remaining arguments". For example, if function div(x,y) = x/y, then div with the parameter x fixed at 1 is another function: div1(y) = div(1,y) = 1/y. This is the same as the function inv that returns the multiplicative inverse of its argument, defined by inv(y) = 1/y. The practical motivation for partial application is that very often the functions obtained by supplying some but not all of the arguments to a function are useful; for example, many languages have a function or operator similar to Implementations[edit]In languages such as ML, Haskell and F#, functions are defined in curried form by default. Supplying fewer than the total number of arguments is referred to as partial application. In languages with first-class functions one can define Scala implements optional partial application with placeholder, e.g. Clojure implements partial application using the The C++ standard library provides
In Java, In Raku, the The Python standard library module In XQuery, an argument placeholder ( Definitions[edit]In the simply-typed lambda calculus with function and product types (λ→,×) partial application, currying and uncurrying can be defined as:
Note that |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?
2018-07-06 分布式链路跟踪 Sleuth 与 Zipkin【Finchley 版】
2015-07-06 ubuntu 12.04 server + OPENACS(TR069)安装配置日记
2015-07-06 windows搭建openacs编译环境