马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
线程函数和线程启动的几种差别情势
在C++中,线程函数和线程启动可以通过多种情势实现。以下是几种常见的情势,并附有相应的示例代码。
1. 利用函数指针启动线程
最根本的方式是利用函数指针来启动线程。
示例代码:- #include <iostream>
- #include <thread>
- void thread_function() {
- std::cout << "Thread function using function pointer." << std::endl;
- }
- int main() {
- std::thread t(&thread_function);
- t.join();
- return 0;
- }
复制代码 2. 利用 Lambda 表达式启动线程
Lambda 表达式提供了一种简便的方式来界说线程函数。
示例代码:- #include <iostream>
- #include <thread>
- int main() {
- std::thread t([] {
- std::cout << "Thread function using lambda expression." << std::endl;
- });
- t.join();
- return 0;
- }
复制代码 3. 利用成员函数启动线程
可以通过类的成员函数来启动线程。
示例代码:- #include <iostream>
- #include <thread>
- class MyClass {
- public:
- void member_function() {
- std::cout << "Thread function using member function." << std::endl;
- }
- };
- int main() {
- MyClass obj;
- std::thread t(&MyClass::member_function, &obj);
- t.join();
- return 0;
- }
复制代码 4. 利用函数对象(Functor)启动线程
可以通过界说一个函数对象(Functor)来启动线程。
示例代码:- #include <iostream>
- #include <thread>
- class ThreadFunctor {
- public:
- void operator()() const {
- std::cout << "Thread function using functor." << std::endl;
- }
- };
- int main() {
- ThreadFunctor functor;
- std::thread t(functor);
- t.join();
- return 0;
- }
复制代码 5. 利用带参数的线程函数
线程函数可以继承参数,并将这些参数转达给线程函数。
示例代码:- #include <iostream>
- #include <thread>
-
- void thread_function_with_params(int id, const std::string& message) {
- std::cout << "Thread ID: " << id << ", Message: " << message << std::endl;
- }
-
- int main() {
- std::thread t(thread_function_with_params, 1, "Hello, Thread!");
- t.join();
- return 0;
- }
复制代码 6. 利用返回值的线程函数(联合 std::future)
利用 std::async 和 std::future 可以启动一个带返回值的线程函数。
示例代码:- #include <iostream>
- #include <future>
- int thread_function_with_return() {
- return 42;
- }
- int main() {
- std::future<int> result = std::async(thread_function_with_return);
- std::cout << "Future result: " << result.get() << std::endl;
- return 0;
- }
复制代码 总结
以上示例展示了C++中启动线程的几种常见情势:
- 利用函数指针
- 利用 Lambda 表达式
- 利用成员函数
- 利用函数对象
- 利用带参数的线程函数
- 利用带返回值的线程函数(联合 std::future)
- 通过这些方法,开发者可以根据具体需求选择最符合的线程启动方式。
|