docs: update memory and threading API docs

This commit is contained in:
2026-03-20 02:35:24 +08:00
parent c5b17239ca
commit fd792b7df1
103 changed files with 2485 additions and 673 deletions

View File

@@ -1,36 +1,44 @@
# Thread::Detach
```cpp
void Detach()
void Detach();
```
分离线程,使其成为后台线程独立运行。分离后,线程的资源将在其终止时自动释放,调用线程不会被阻塞
分离线程,使其在后台独立运行。调用 `Detach()` 后,线程不再受 `Thread` 对象管理,其生命周期由 C++ 运行时库自行管理,直到线程函数执行完毕
分离后的线程成为"守护线程",其资源在线程结束时自动由运行时回收。与 `Join()` 不同,`Detach()` 只能调用一次。
**警告:** 分离线程时必须确保其访问的所有数据在线程运行期间保持有效。分离后无法通过 `Thread` 对象同步或等待线程。
**参数:**
**返回:**
**复杂度** O(1)
**注意:**
- 分离后的线程无法再被 Join 或进行任何同步操作。
- 确保分离线程的所有资源访问都是线程安全的,因为主线程可能在分离线程结束前退出。
- 如果 Thread 对象在分离线程结束前被销毁,行为取决于具体实现。
**线程安全**
**示例:**
```cpp
Thread background;
background.Start([]() {
printf("Background task running\n");
for (int i = 0; i < 3; ++i) {
Thread::Sleep(500);
printf("Background: tick %d\n", i);
}
}, "BackgroundThread");
#include "XCEngine/Threading/Thread.h"
#include <iostream>
background.Detach();
printf("Main thread continues immediately\n");
using namespace XCEngine::Threading;
int main() {
Thread t;
t.Start([]() {
for (int i = 0; i < 3; ++i) {
std::cout << "Detached thread running: " << i << std::endl;
Thread::Sleep(50);
}
}, "DetachedThread");
std::cout << "Thread detached, main continues..." << std::endl;
t.Detach();
Thread::Sleep(200);
return 0;
}
```
## 相关文档