chore: migrate project into clean repository

This commit is contained in:
yuuux
2026-08-13 16:50:52 +08:00
commit d1d25a09e7
27405 changed files with 9422808 additions and 0 deletions

View File

@@ -0,0 +1,17 @@
cmake_minimum_required(VERSION 3.13)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
find_package(listenai-cmake REQUIRED HINTS $ENV{ARCS_BASE})
project(arcs)
listenai_add_executable(${PROJECT_NAME})
target_sources(${PROJECT_NAME} PRIVATE
src/main.cpp
src/future_promise_test.cpp
src/mutex_condvar_test.cpp
)
listenai_include_directories(src)

View File

@@ -0,0 +1 @@
osource "$ARCS_BASE/Kconfig"

View File

@@ -0,0 +1,170 @@
C++ 多线程示例
===============
功能说明
--------
演示 C++ 标准库中的多线程编程特性,包括线程创建、异常处理、``std::future``/``std::promise`` 异步编程以及互斥锁和条件变量的使用。本示例展示了如何在多线程环境下安全地共享数据和进行线程同步。
硬件连接
--------
无需外部连接,多线程为软件功能,不依赖硬件资源。
示例内容
--------
1. 演示 C++ 异常处理机制(``try-catch``)
2. 演示基本线程创建和同步(``std::thread``)
3. 演示 ``std::future`` 和 ``std::promise`` 异步编程
4. 演示 ``std::packaged_task`` 和 ``std::async`` 的使用
5. 演示互斥锁(``std::mutex``)保护共享数据
6. 演示条件变量(``std::condition_variable``)实现生产者-消费者模式
编译
--------
.. include:: /sample_build.rst
烧录固件
--------
.. include:: /sample_flash.rst
预期输出
--------
.. code-block:: text
Caught a runtime error: Error occurred
Thread 1: 1
Thread 2: 1
Thread 1: 2
Thread 2: 2
Thread 1: 3
Thread 2: 3
Thread 1: 4
Thread 2: 4
Thread 1: 5
Thread 2: 5
Both threads completed.
======= Starting Future/Promise Tests =======
=== Basic Future/Promise Example ===
Promise thread: calculating value...
Main thread: waiting for value...
Promise thread: value set
Main thread: received value 42
=== Another Future/Promise Example ===
Another promise thread: calculating value...
Main thread: waiting for another value...
Another promise thread: value set
Main thread: received another value 100
=== Packaged Task Example ===
Packaged task: calculating result for 5...
Main thread: waiting for packaged task result...
Main thread: packaged task result is 25
=== Async Example ===
Starting async task with launch::async...
Main thread: doing other work while waiting...
Async task: working in separate thread...
Main thread: getting async result...
Main thread: async result is 100
Starting async task with launch::deferred...
Main thread: calling get() on deferred task...
Deferred task: executing in caller's thread when get() is called...
Main thread: deferred result is 200
======= Future/Promise Tests Completed =======
======= Starting Mutex/Condition Variable Tests =======
=== Mutex and Condition Variable Tests ===
=== Basic Mutex Example ===
Starting two threads that increment a counter with mutex protection...
Final counter value: 20000
Expected value: 20000
=== Basic Condition Variable Example ===
Starting consumer thread...
Starting producer thread...
Produced: 1
Consumed: 1
Produced: 2
Consumed: 2
...
======= Mutex/Condition Variable Tests Completed =======
核心 API
--------
.. list-table::
:header-rows: 1
* - API
- 说明
* - ``std::thread``
- C++11 线程类,用于创建和管理线程
* - ``std::future``
- 异步操作结果的占位符
* - ``std::promise``
- 用于在线程间传递值或异常
* - ``std::mutex``
- 互斥锁,保护共享资源
* - ``std::condition_variable``
- 条件变量,用于线程间同步
* - ``std::async``
- 异步执行函数并返回 future
* - ``std::packaged_task``
- 封装可调用对象,用于异步执行
关键代码
--------
.. code-block:: cpp
// 异常处理
try {
throw std::runtime_error("Error occurred");
} catch (const std::runtime_error &e) {
std::cout << "Caught a runtime error: " << e.what() << std::endl;
}
// 创建和同步线程
std::thread t1(printNumbers, 1);
std::thread t2(printNumbers, 2);
t1.join();
t2.join();
// 使用 promise 和 future
std::promise<int> intPromise;
std::future<int> intFuture = intPromise.get_future();
std::thread t(promiseFunction, std::move(intPromise));
int value = intFuture.get(); // 等待并获取值
// 使用互斥锁保护共享数据(推荐使用 lock_guard)
std::mutex mtx;
{
std::lock_guard<std::mutex> lock(mtx);
// 访问共享数据(自动加锁和解锁)
counter++;
}
注意事项
--------
1. **线程同步**: 多个线程访问共享数据时必须使用互斥锁或其他同步机制保护
2. **线程生命周期**: 必须调用 ``join()`` 或 ``detach()`` 来管理线程生命周期,否则程序会异常终止
3. **异常安全**: 在多线程环境中,异常处理需要特别注意,确保资源正确释放
4. **死锁避免**: 使用多个互斥锁时要注意避免死锁,建议按固定顺序获取锁
5. **条件变量**: 使用条件变量时必须配合互斥锁,等待条件时必须使用 ``std::unique_lock``
6. **Future/Promise**: ``std::promise`` 只能设置一次值,多次设置会导致异常

View File

@@ -0,0 +1,177 @@
#!/bin/bash
set -e
usage() {
echo "使用方式: $0 [选项]"
echo "选项:"
echo " -S, --Source <path> 指定项目源码路径 (默认为当前脚本所在目录)"
echo " -t, --target <target> 指定构建目标 (如 menuconfig)"
echo " -C, --Clean 清理构建目录"
echo " -B, --build 构建输出目录"
echo " -h, --help 显示此帮助信息"
echo " -r, --release 以 Release 模式构建 (移除 DEBUG_PATH 信息)"
echo " -w, --warnings-as-errors 将警告视为错误"
echo " -D<var>=<value> 传递 CMake 变量 (可多次使用)"
echo ""
echo "示例:"
echo " $0 -S samples/helloworld -DBOARD=arcs_mini 指定板型构建"
echo " $0 -S samples/helloworld -DBOARD=arcs_evb 使用 EVB 板型"
echo " $0 -S samples/helloworld -t menuconfig -DBOARD=arcs_mini 运行 menuconfig"
echo " $0 -C -S samples/helloworld -DBOARD=arcs_mini 清理并重新构建"
echo " $0 -S samples/helloworld -DBOARD=my_board -DBOARD_SEARCH_PATH=/path/to/boards 使用自定义板型"
exit 1
}
SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
PROJECT_PATH="$SCRIPT_DIR"
TARGET=""
CLEAN=false
OUTPUT="build"
WARNINGS_AS_ERRORS=false
RELEASE=false
ARCS_BASE_DIR_NAME="arcs-sdk"
ARCS_DEV_TOOLS_DIR_NAME="listenai-dev-tools"
ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME="gcc"
ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME="listenai-tools"
find_arcs_base() {
local current_dir=$(cd "$(dirname "$0")" && pwd)
local dir_name="$ARCS_BASE_DIR_NAME"
while [ "$current_dir" != "/" ]; do
if [ -d "$current_dir/$dir_name" ]; then
echo "Found ARCS_BASE: $current_dir/$dir_name"
export ARCS_BASE="$current_dir/$dir_name"
return 0
fi
current_dir=$(dirname "$current_dir")
done
echo "ARCS_BASE not found, Please add ARCS_BASE environment variable or set ARCS_BASE_DIR_NAME to the correct directory."
echo "Current Target ARCS_BASE directory name: $ARCS_BASE_DIR_NAME."
exit 1
}
find_dev_tools() {
local current_dir=$(cd "$(dirname "$0")" && pwd)
local dir_name="$ARCS_DEV_TOOLS_DIR_NAME"
echo "trying to find $dir_name in parent directories..."
while [ "$current_dir" != "/" ]; do
if [ -d "$current_dir/$dir_name" ]; then
echo "Found $dir_name: $current_dir/$dir_name"
if [ -d "$current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME" ]; then
echo "Found LISTENAI_TOOLS_PATH: $current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME"
export LISTENAI_TOOLS_PATH="$current_dir/$dir_name/$ARCS_DEV_TOOL_LISTENAI_TOOLS_DIR_NAME"
fi
if [ -d "$current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME" ]; then
echo "Found NUCLEI_TOOLCHAIN_PATH: $current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME"
export NUCLEI_TOOLCHAIN_PATH="$current_dir/$dir_name/$ARCS_DEV_TOOL_TOOLCHAIN_DIR_NAME"
fi
return 0
fi
current_dir=$(dirname "$current_dir")
done
}
while [[ $# -gt 0 ]]; do
case $1 in
-S|--Source)
PROJECT_PATH="$2"
shift 2
;;
-B|--build)
OUTPUT="$2"
shift 2
;;
-t|--target)
TARGET="$2"
shift 2
;;
-C|--Clean)
CLEAN=true
shift 1
;;
-w|--warnings-as-errors)
WARNINGS_AS_ERRORS=true
shift 1
;;
-h|--help)
usage
;;
-r|--release)
RELEASE=true
shift 1
;;
-D*)
CMAKE_VARS+=("$1")
shift 1
;;
*)
echo "未知参数: $1"
usage
;;
esac
done
echo "Source: $PROJECT_PATH"
echo "Target: $TARGET"
echo "Clean : $CLEAN"
if [ -z "$LISTENAI_TOOLS_PATH" ] || [ -z "$NUCLEI_TOOLCHAIN_PATH" ]; then
find_dev_tools
fi
if [ -z "${LISTENAI_TOOLS_PATH}" ]; then
export LISTENAI_TOOLS_PATH="请添加 LISTENAI_TOOLS_PATH 环境变量,或在此行设置正确的路径"
echo "请添加 LISTENAI_TOOLS_PATH 环境变量或者修改脚本后, 注释脚本第 $LINENO 行";exit 1;
fi
if [ -z "${NUCLEI_TOOLCHAIN_PATH}" ]; then
export NUCLEI_TOOLCHAIN_PATH="请添加 NUCLEI_TOOLCHAIN_PATH 环境变量,或在此行设置正确的路径"
echo "请添加 NUCLEI_TOOLCHAIN_PATH 环境变量或者修改脚本后, 注释脚本第 $LINENO 行";exit 1;
fi
############### 下面代码不用修改 ##################
# 构建工具的位置
CMAKE_PROGRAM="$LISTENAI_TOOLS_PATH/cmake/bin/cmake"
NINJA_PROGRAM="$LISTENAI_TOOLS_PATH/ninja/ninja"
# 配置环境变量 ARCS_BASE
if [ -z "$ARCS_BASE" ]; then
find_arcs_base
fi
if [ "$CLEAN" = true ]; then
rm -rf $OUTPUT
fi
# Initialize CMAKE_VARS array if it doesn't exist
declare -a CMAKE_VARS
# Add warnings-as-errors flag if enabled
if [ "$WARNINGS_AS_ERRORS" = true ]; then
CMAKE_VARS+=("-DCMAKE_C_FLAGS=-Werror")
CMAKE_VARS+=("-DCMAKE_CXX_FLAGS=-Werror")
echo "Treating warnings as errors"
fi
# Add release flags if enabled
if [ "$RELEASE" = true ]; then
CMAKE_VARS+=("-DENABLE_DEBUG_PATH=OFF")
echo "Release mode enabled (-DENABLE_DEBUG_PATH=OFF)"
fi
$CMAKE_PROGRAM -B "$OUTPUT" -G Ninja -S "$PROJECT_PATH" \
-DCMAKE_MAKE_PROGRAM="$NINJA_PROGRAM" \
"${CMAKE_VARS[@]}"
if [ -z "$TARGET" ]; then
$CMAKE_PROGRAM --build "$OUTPUT" -j4
else
$CMAKE_PROGRAM --build "$OUTPUT" --target "$TARGET"
fi

View File

@@ -0,0 +1,4 @@
# 项目可根据需要在此文件中设置对应的配置
CONFIG_MEM_CONFIG=y
CONFIG_FREERTOS_STATIC_ALLOCATION_ENABLE=1
CONFIG_FREERTOS_CPP11=y

View File

@@ -0,0 +1,8 @@
tests:
samples.cpp.threads:
programmer: arcs
runner: uart
log_analyzer:
type: "regex"
pattern: "Variable Tests Completed"

View File

@@ -0,0 +1,118 @@
#include "future_promise_test.h"
#include <future>
// 使用promise设置值,future获取值的示例
void promiseFunction(std::promise<int> intPromise) {
std::cout << "Promise thread: calculating value..." << std::endl;
// 模拟一些计算工作
std::this_thread::sleep_for(std::chrono::seconds(2));
// 设置promise的值
intPromise.set_value(42);
std::cout << "Promise thread: value set" << std::endl;
}
// 另一个简单的promise示例函数
void anotherPromiseFunction(std::promise<int> intPromise) {
std::cout << "Another promise thread: calculating value..." << std::endl;
// 模拟一些计算工作
std::this_thread::sleep_for(std::chrono::seconds(1));
// 设置promise的值
intPromise.set_value(100);
std::cout << "Another promise thread: value set" << std::endl;
}
// 使用packaged_task封装函数
int calculateValue(int x) {
std::cout << "Packaged task: calculating result for " << x << "..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(1));
return x * x;
}
// 展示std::async的使用
void asyncExample() {
std::cout << "\n=== Async Example ===" << std::endl;
// 使用std::async启动异步任务
std::cout << "Starting async task with launch::async..." << std::endl;
std::future<int> asyncResult = std::async(std::launch::async, []{
std::cout << "Async task: working in separate thread..." << std::endl;
std::this_thread::sleep_for(std::chrono::seconds(2));
return 100;
});
// 可以在此处执行其他工作
std::cout << "Main thread: doing other work while waiting..." << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(500));
// 获取结果
std::cout << "Main thread: getting async result..." << std::endl;
int result = asyncResult.get();
std::cout << "Main thread: async result is " << result << std::endl;
// 延迟任务示例
std::cout << "\nStarting async task with launch::deferred..." << std::endl;
std::future<int> deferredResult = std::async(std::launch::deferred, []{
std::cout << "Deferred task: executing in caller's thread when get() is called..." << std::endl;
return 200;
});
// 调用get()才会执行延迟任务
std::cout << "Main thread: calling get() on deferred task..." << std::endl;
result = deferredResult.get();
std::cout << "Main thread: deferred result is " << result << std::endl;
}
void runFuturePromiseTests() {
// 基本的Future/Promise 示例
std::cout << "=== Basic Future/Promise Example ===" << std::endl;
// 创建promise和对应的future
std::promise<int> intPromise;
std::future<int> intFuture = intPromise.get_future();
// 启动线程,并传递promise
std::thread promiseThread(promiseFunction, std::move(intPromise));
// 主线程等待future的值
std::cout << "Main thread: waiting for value..." << std::endl;
int value = intFuture.get(); // 阻塞直到promise设置值
std::cout << "Main thread: received value " << value << std::endl;
promiseThread.join();
// 另一个Future/Promise 示例
std::cout << "\n=== Another Future/Promise Example ===" << std::endl;
std::promise<int> anotherPromise;
std::future<int> anotherFuture = anotherPromise.get_future();
std::thread anotherThread(anotherPromiseFunction, std::move(anotherPromise));
std::cout << "Main thread: waiting for another value..." << std::endl;
int anotherValue = anotherFuture.get();
std::cout << "Main thread: received another value " << anotherValue << std::endl;
anotherThread.join();
// Packaged Task示例
std::cout << "\n=== Packaged Task Example ===" << std::endl;
// 创建一个packaged_task,封装calculateValue函数
std::packaged_task<int(int)> task(calculateValue);
// 获取future
std::future<int> taskFuture = task.get_future();
// 在另一个线程中执行task
std::thread taskThread(std::move(task), 5);
// 等待结果
std::cout << "Main thread: waiting for packaged task result..." << std::endl;
int taskResult = taskFuture.get();
std::cout << "Main thread: packaged task result is " << taskResult << std::endl;
taskThread.join();
// 异步任务示例
asyncExample();
}

View File

@@ -0,0 +1,24 @@
#ifndef FUTURE_PROMISE_TEST_H
#define FUTURE_PROMISE_TEST_H
#include <iostream>
#include <thread>
#include <future>
#include <chrono>
// 使用promise设置值,future获取值的示例
void promiseFunction(std::promise<int> intPromise);
// 带有异常处理的promise示例
void promiseFunctionWithException(std::promise<int> intPromise);
// 使用packaged_task封装函数
int calculateValue(int x);
// 展示std::async的使用
void asyncExample();
// 运行所有future和promise测试
void runFuturePromiseTests();
#endif // FUTURE_PROMISE_TEST_H

View File

@@ -0,0 +1,43 @@
#include <iostream>
#include <thread>
#include "future_promise_test.h"
#include "mutex_condvar_test.h"
void printNumbers(int threadID) {
for (int i = 1; i <= 5; ++i) {
std::cout << "Thread " << threadID << ": " << i << std::endl;
}
}
int main(int argc, char **argv)
{
try {
throw std::runtime_error("Error occurred");
} catch (const std::runtime_error &e) {
std::cout << "Caught a runtime error: " << e.what() << std::endl;
} catch (const std::exception &e) {
std::cout << "Caught a standard exception: " << e.what() << std::endl;
} catch (...) {
std::cout << "Caught an unknown exception" << std::endl;
}
std::thread t1(printNumbers, 1);
std::thread t2(printNumbers, 2);
t1.join();
t2.join();
std::cout << "Both threads completed." << std::endl;
// 运行Future和Promise的测试
std::cout << "\n\n======= Starting Future/Promise Tests =======\n" << std::endl;
runFuturePromiseTests();
std::cout << "\n======= Future/Promise Tests Completed =======\n" << std::endl;
// 运行Mutex和Condition Variable的测试
std::cout << "\n\n======= Starting Mutex/Condition Variable Tests =======\n" << std::endl;
runMutexCondVarTests();
std::cout << "\n======= Mutex/Condition Variable Tests Completed =======\n" << std::endl;
return 0;
}

View File

@@ -0,0 +1,151 @@
#include "mutex_condvar_test.h"
// 基本互斥锁使用示例
void basicMutexExample() {
std::cout << "\n=== Basic Mutex Example ===" << std::endl;
std::mutex mtx;
int counter = 0;
std::cout << "Starting two threads that increment a counter with mutex protection..." << std::endl;
// 创建两个线程,都会增加计数器
std::thread t1(mutexProtectedCounter, std::ref(mtx), std::ref(counter), 10000);
std::thread t2(mutexProtectedCounter, std::ref(mtx), std::ref(counter), 10000);
t1.join();
t2.join();
std::cout << "Final counter value: " << counter << std::endl;
std::cout << "Expected value: 20000" << std::endl;
}
// 使用互斥锁保护共享数据的函数
void mutexProtectedCounter(std::mutex& mtx, int& counter, int iterations) {
for (int i = 0; i < iterations; i++) {
// 锁定互斥锁,确保只有一个线程可以访问计数器
std::lock_guard<std::mutex> lock(mtx);
counter++; // 临界区:安全地修改共享变量
}
}
// 使用条件变量的生产者函数
void producer(std::mutex& mtx, std::condition_variable& cv, std::queue<int>& queue, int items) {
for (int i = 1; i <= items; i++) {
{
std::lock_guard<std::mutex> lock(mtx);
queue.push(i);
std::cout << "Produced: " << i << std::endl;
}
// 通知等待的消费者
cv.notify_one();
// 生产速度稍慢于消费
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
// 使用条件变量的消费者函数
void consumer(std::mutex& mtx, std::condition_variable& cv, std::queue<int>& queue, bool& done) {
while (!done) {
std::unique_lock<std::mutex> lock(mtx);
// 等待队列非空或完成标志
cv.wait(lock, [&queue, &done]() {
return !queue.empty() || done;
});
// 检查是否只是因为done标志而被唤醒
if (queue.empty() && done) {
break;
}
// 处理队列中的元素
int value = queue.front();
queue.pop();
std::cout << "Consumed: " << value << std::endl;
// 解锁互斥锁,以便生产者可以继续
lock.unlock();
// 模拟处理数据的时间
std::this_thread::sleep_for(std::chrono::milliseconds(50));
}
}
// 展示多个线程的条件变量使用
void multipleConsumersExample() {
std::cout << "\n=== Multiple Consumers Example ===" << std::endl;
std::mutex mtx;
std::condition_variable cv;
std::queue<int> queue;
std::vector<std::thread> consumers;
bool done = false;
// 创建多个消费者线程
std::cout << "Starting 3 consumer threads..." << std::endl;
for (int i = 0; i < 3; i++) {
consumers.emplace_back(consumer, std::ref(mtx), std::ref(cv), std::ref(queue), std::ref(done));
}
// 创建生产者线程
std::cout << "Starting producer thread..." << std::endl;
std::thread producerThread(producer, std::ref(mtx), std::ref(cv), std::ref(queue), 15);
// 等待生产者完成
producerThread.join();
// 通知所有消费者已经没有更多数据了
{
std::lock_guard<std::mutex> lock(mtx);
done = true;
}
cv.notify_all();
// 等待所有消费者完成
for (auto& t : consumers) {
t.join();
}
std::cout << "All threads completed successfully" << std::endl;
}
void runMutexCondVarTests() {
std::cout << "=== Mutex and Condition Variable Tests ===" << std::endl;
// 运行基本互斥锁示例
basicMutexExample();
// 简单的条件变量示例
std::cout << "\n=== Basic Condition Variable Example ===" << std::endl;
std::mutex mtx;
std::condition_variable cv;
std::queue<int> queue;
bool done = false;
// 创建消费者线程
std::cout << "Starting consumer thread..." << std::endl;
std::thread consumerThread(consumer, std::ref(mtx), std::ref(cv), std::ref(queue), std::ref(done));
// 创建生产者线程
std::cout << "Starting producer thread..." << std::endl;
std::thread producerThread(producer, std::ref(mtx), std::ref(cv), std::ref(queue), 5);
// 等待生产者完成
producerThread.join();
// 通知消费者已经没有更多数据了
{
std::lock_guard<std::mutex> lock(mtx);
done = true;
}
cv.notify_one();
// 等待消费者完成
consumerThread.join();
// 运行多消费者示例
multipleConsumersExample();
}

View File

@@ -0,0 +1,30 @@
#ifndef MUTEX_CONDVAR_TEST_H
#define MUTEX_CONDVAR_TEST_H
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <chrono>
#include <queue>
#include <vector>
// 基本互斥锁使用示例函数
void basicMutexExample();
// 使用互斥锁保护共享数据的函数
void mutexProtectedCounter(std::mutex& mtx, int& counter, int iterations);
// 使用条件变量的生产者函数
void producer(std::mutex& mtx, std::condition_variable& cv, std::queue<int>& queue, int items);
// 使用条件变量的消费者函数
void consumer(std::mutex& mtx, std::condition_variable& cv, std::queue<int>& queue, bool& done);
// 展示多个线程的条件变量使用
void multipleConsumersExample();
// 运行所有mutex和condition_variable测试
void runMutexCondVarTests();
#endif // MUTEX_CONDVAR_TEST_H