c++ 异步多线程实例
时间: 2023-08-16 16:17:08 浏览: 55
下面是一个简单的 C++ 异步多线程实例:
```cpp
#include <iostream>
#include <thread>
#include <future>
using namespace std;
int factorial(int n) {
int res = 1;
for (int i = n; i > 1; --i) {
res *= i;
}
return res;
}
int main() {
int x = 5;
// 异步执行阶乘计算
future<int> fut = async(factorial, x);
cout << "正在计算 " << x << " 的阶乘..." << endl;
// 执行其他任务
this_thread::sleep_for(chrono::milliseconds(1000));
// 获取异步计算结果
int result = fut.get();
cout << x << " 的阶乘是 " << result << endl;
return 0;
}
```
在这个例子中,`factorial()` 函数计算一个整数的阶乘。`async()` 函数将该函数异步执行,并返回一个 `future` 对象,该对象可以用于获取异步计算的结果。在主线程中,我们可以执行其他任务,然后调用 `get()` 函数获取异步计算结果。
相关问题
qt/c++ tcp多线程客户端(
Qt/C++是一种开发语言和框架,可以用于创建跨平台的应用程序。其中,Qt提供了很多库和工具,可以方便地创建网络应用程序,例如TCP多线程客户端。
TCP多线程客户端是一种网络应用程序,可以向TCP服务器发送数据,并接收服务器返回的数据。多线程则意味着可以同时发送和接收多个数据流,提高了应用程序的效率和响应速度。
使用Qt/C++实现TCP多线程客户端需要以下步骤:
1. 创建QTcpSocket对象,该对象用于建立TCP连接、发送数据和接收数据。
2. 创建QThread对象,将其作为QTcpSocket对象的父对象,并将QTcpSocket对象移动到该线程中。
3. 在QThread对象中实现数据发送和接收的函数,该函数运行在子线程中,可以异步地发送和接收数据。
4. 在主线程中创建QTcpSocket对象和QThread对象的实例,并将它们连接起来。
5. 启动QThread对象,开始发送和接收数据。
在实现过程中,需要注意线程安全问题,例如需要将QTcpSocket对象的信号连接到主线程中的槽函数。此外,还需要考虑异常处理,例如连接失败时需要发送错误消息。
总之,使用Qt/C++实现TCP多线程客户端是一项有挑战的任务,但通过良好的设计和实践,可以创建高效和可靠的网络应用程序。
C++ 多线程 回调
C++多线程回调可以通过线程池技术实现。具体实现思路如下:
1. 创建一个线程池,线程池中包含多个线程,这些线程都是可重用的资源。
2. 在主线程中创建一个任务队列,将需要异步处理的任务加入到任务队列中。
3. 线程池中的线程会不断地从任务队列中取出任务进行处理。
4. 当任务处理完成后,线程会将处理结果通过回调函数返回给主线程。
下面是一个简单的C++多线程回调的例子:
```cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <queue>
#include <functional>
using namespace std;
class ThreadPool {
public:
ThreadPool(int numThreads) : stop(false) {
for (int i = 0; i < numThreads; ++i) {
threads.emplace_back(
[this] {
for (;;) {
function<void()> task;
{
unique_lock<mutex> lock(this->queue_mutex);
this->condition.wait(lock,
[this] { return this->stop || !this->tasks.empty(); });
if (this->stop && this->tasks.empty())
return;
task = move(this->tasks.front());
this->tasks.pop();
}
task();
}
}
);
}
}
template<class F>
void enqueue(F&& f) {
{
unique_lock<mutex> lock(queue_mutex);
tasks.emplace(forward<F>(f));
}
condition.notify_one();
}
~ThreadPool() {
{
unique_lock<mutex> lock(queue_mutex);
stop = true;
}
condition.notify_all();
for (thread& worker : threads)
worker.join();
}
private:
vector<thread> threads;
queue<function<void()>> tasks;
mutex queue_mutex;
condition_variable condition;
bool stop;
};
void asyncTask(int x, int y, function<void(int)> callback) {
int result = x + y;
callback(result);
}
int main() {
ThreadPool pool(4);
pool.enqueue([] {
cout << "Task 1" << endl;
});
pool.enqueue([] {
cout << "Task 2" << endl;
});
pool.enqueue([] {
cout << "Task 3" << endl;
});
pool.enqueue([] {
cout << "Task 4" << endl;
});
pool.enqueue([] {
cout << "Task 5" << endl;
});
pool.enqueue([] {
asyncTask(1, 2, [](int result) {
cout << "Result: " << result << endl;
});
});
return 0;
}
```