doc: Update cpp.md (#254)
开始添加多线程部分,主要添加了线程的创建、销毁和this_thread的所有函数 尚未开始的内容:锁、互斥量、线程同步
This commit is contained in:
parent
9879fabc78
commit
db7a9aa6f9
65
docs/cpp.md
65
docs/cpp.md
@ -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++ 预处理器
|
C++ 预处理器
|
||||||
------------
|
------------
|
||||||
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user