温馨提示×

c++ thread怎么使用

c++
小亿
95
2023-09-14 22:50:43
栏目: 编程语言

C++中的线程可以通过使用std::thread类来创建和管理。下面是一个简单的示例代码,展示了如何在C++中使用线程:

#include <iostream>
#include <thread>
// 线程函数
void threadFunction() {
std::cout << "Hello from thread!" << std::endl;
}
int main() {
// 创建线程对象并传入线程函数
std::thread myThread(threadFunction);
// 主线程继续执行
std::cout << "Hello from main thread!" << std::endl;
// 等待线程执行完毕
myThread.join();
return 0;
}

在上面的代码中,我们创建了一个名为myThread的线程对象,并将threadFunction作为线程函数传递给它。然后,主线程继续执行,在执行完std::cout语句后,通过调用myThread.join()等待线程执行完毕。

此外,还可以传递参数给线程函数:

#include <iostream>
#include <thread>
// 线程函数
void threadFunction(int n) {
std::cout << "Hello from thread! Number: " << n << std::endl;
}
int main() {
int numThreads = 5;
std::thread threads[numThreads];
// 创建多个线程对象,并传入线程函数和参数
for (int i = 0; i < numThreads; i++) {
threads[i] = std::thread(threadFunction, i);
}
// 主线程继续执行
std::cout << "Hello from main thread!" << std::endl;
// 等待所有线程执行完毕
for (int i = 0; i < numThreads; i++) {
threads[i].join();
}
return 0;
}

在这个示例中,我们创建了一个包含5个线程对象的数组,并通过循环在每个线程对象上调用std::thread构造函数来创建线程。每个线程对象都传递了不同的参数给线程函数threadFunction

需要注意的是,在使用线程时需要小心处理共享资源的访问,以避免竞态条件和数据竞争的问题。可以使用互斥量(std::mutex)来对共享资源进行同步访问,或者使用其他线程安全的容器和工具。

0