C++ 多线程 std::thread::get_id
C++ 多线程 std::thread::get_id
- 1. `std::thread::get_id`
- 2. Parameters
- 3. Return value
- 4. Examples
- 5. Data races (数据竞争)
- 6. Exception safety (异常安全性)
- References
https://cplusplus.com/reference/thread/thread/get_id/
public member function
1. std::thread::get_id
id get_id() const noexcept;
Returns the thread id.
If the thread object is joinable, the function returns a value that uniquely identifies the thread.
If the thread object is not joinable, the function returns a default-constructed object of member type std::thread::id
.
2. Parameters
none
3. Return value
An object of member type std::thread::id
that uniquely identifies the thread (if joinable), or default-constructed (if not joinable)
4. Examples
#include <iostream>
#include <thread>
#include <chrono>std::thread::id main_thread_id = std::this_thread::get_id();void is_main_thread() {if (main_thread_id == std::this_thread::get_id()) {std::cout << "This is the main thread." << std::endl;}else {std::cout << "This is not the main thread." << std::endl;}
}int main() {is_main_thread();std::cout << "Yongqiang Cheng" << std::endl;std::thread th(is_main_thread);th.join();return 0;
}
This is the main thread.
Yongqiang Cheng
This is not the main thread.
请按任意键继续. . .
5. Data races (数据竞争)
The object is accessed.
6. Exception safety (异常安全性)
No-throw guarantee: never throws exceptions.
References
[1] Yongqiang Cheng, https://yongqiang.blog.csdn.net/
[2] std::thread::get_id
, https://cplusplus.com/reference/thread/thread/get_id/