Skip to content

Commit

Permalink
doc: Update cpp.md (#254)
Browse files Browse the repository at this point in the history
开始添加多线程部分,主要添加了线程的创建、销毁和this_thread的所有函数

尚未开始的内容:锁、互斥量、线程同步
  • Loading branch information
LiuYuan-SHU committed Dec 30, 2022
1 parent 9879fab commit db7a9aa
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions docs/cpp.md
Original file line number Diff line number Diff line change
Expand Up @@ -626,6 +626,71 @@ std::for_each(vec.begin(), vec.end(), [](int& ele) -> void
});
```
## C++多线程
> g++编译选项:`std=c++11`
>
> 包含头文件:
>
> + `#include <thread>`:C++多线程库
> + `#include <mutex>`:C++互斥量库
### 线程的创建
以普通函数作为线程入口函数:
```c++
void thread_entry_function_1() { }
void thread_entry_function_2(int val) { }
std::thread my_thread_1(thread_entry_function_1);
std::thread my_thread_2(thread_entry_function_2, 5);
```

以类对象作为线程入口函数:

```c++
class Entry
{
void operator()() { }
void entry_function() { }
};

Entry entry;
// 调用operator()()
std::thread my_thread_1(entry);
// 调用Entry::entry_function
std::thread my_thread_2(&Entry::entry_function, &entry);
```
以lambda表达式作为线程入口函数:
```c++
std::thread my_thread([]() -> void
{
// ...
});
```

### 线程的销毁

```c++
thread my_thread;
// 阻塞
my_thread.join();
// 非阻塞
my_thread.detach();
```

### `this_thread`

```c++
std::this_thread::get_id(); // 获取当前线程ID
std::this_thread::sleep_for(); // 使当前线程休眠一段指定时间
std::this_thread::sleep_until();// 使当前线程休眠到指定时间
std::this_thread::yield(); // 暂停当前线程的执行,让别的线程执行
```

C++ 预处理器
------------

Expand Down

0 comments on commit db7a9aa

Please sign in to comment.