1.先容
在C++中,线程是实现并行开发的核心工具之一。C++11引入了尺度库<thread>,提供了对多线程编程的支持。通过线程,程序可以同时执行多个使命,从而提高性能和相应速度。
线程池先容在这篇博客——C++之线程池(Thread Pool)-CSDN博客
2.基本概念
线程——是操纵系统能够调度的最小执行单位。一个进程可以包罗多个进程,所有线程共享进程的内存空间。
并发——多个线程同时执行,但可能交替占用CPU资源。
并行——多个线程同时执行,且同时占用多个CPU资源。
3.C++中的线程库
C++11引入了<thread>头文件,提供了以下核心功能:
thread——用于创建于管理线程。
mutex——用于实现线程间的互斥锁。
condition_variable——用于实现线程间的条件变量。
future和promise——用于异步使命的结果获取。
4.用法
(1)创建线程。利用thread创建线程,并指定线程执行的函数。例如:
- #include <iostream>
- #include <thread>
- void threadFunction() {
- std::cout << "Hello from thread!" << std::endl;
- }
- int main() {
- // 创建线程并执行 threadFunction
- std::thread t(threadFunction);
- // 等待线程结束,回收
- t.join();
- std::cout << "Main thread finished." << std::endl;
- return 0;
- }
复制代码 通过上面的简单例子,可以知道如何创建线程并指定线程执行的函数。
(2)线程的参数传递。可以向线程函数传递参数。例如:
- #include <iostream>
- #include <thread>
- void printMessage(const std::string& message) {
- std::cout << "Message: " << message << std::endl;
- }
- int main() {
- std::string msg = "Hello, World!";
- std::thread t(printMessage, msg);
- t.join();
- return 0;
- }
复制代码 如果需要引用传递,可以利用std::ref。
(3)线程的同步。多个线程访问共享资源时,需要利用同步机制制止竞争条件。
1.互斥锁(mutex)
- #include <iostream>
- #include <thread>
- #include <mutex>
- std::mutex mtx;
- void printBlock(char c) {
- std::unique_lock<std::mutex> lock(mtx);
- for (int i = 0; i < 10; ++i) {
- std::cout << c;
- }
- std::cout << std::endl;
- }
- int main() {
- std::thread t1(printBlock, '*');
- std::thread t2(printBlock, '$');
- t1.join();
- t2.join();
- return 0;
- }
复制代码 mutex——用于保护共享资源。
unique_lock——主动管理锁的生命周期。
2.条件变量(condition_variable)
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <condition_variable>
- std::mutex mtx;
- std::condition_variable cv;
- bool ready = false;
- void printMessage(int id) {
- std::unique_lock<std::mutex> lock(mtx);
- cv.wait(lock, [] { return ready; });
- std::cout << "Thread " << id << " is running." << std::endl;
- }
- int main() {
- std::thread threads[3];
- for (int i = 0; i < 3; ++i) {
- threads[i] = std::thread(printMessage, i);
- }
- std::this_thread::sleep_for(std::chrono::seconds(1));
- {
- std::unique_lock<std::mutex> lock(mtx);
- ready = true;
- }
- cv.notify_all();
- for (auto& t : threads) {
- t.join();
- }
- return 0;
- }
复制代码 condition_variable:用于线程间的条件同步。三个线程都阻塞在cv.wait。
cv.wait(lock,predicate):等候条件满意。阻塞期间会释放锁。
cv.notify_all():关照所有等候线程。
上边程序的运行流程是三个线程调用执行函数,阻塞等候,等候1s后,加锁,条件满意继续执行后续函数,从而实现三个线程同步执行。
(4)异步使命。利用 std::async和 std::future实现异步使命。
- #include <iostream>
- #include <future>
- int computeSum(int a, int b) {
- return a + b;
- }
- int main() {
- std::future<int> result = std::async(computeSum, 10, 20);
- std::cout << "Result: " << result.get() << std::endl;
- return 0;
- }
复制代码 std::async:启动一个异步使命。作用就是制止阻塞主线程。
std::future:用于获取异步使命的结果。
5.总结
- C++11 提供了强大的多线程支持,包罗线程创建、互斥锁、条件变量和异步使命。
- 在实际开发中,需要注意线程安全和资源管理题目。
如有错误,敬请指正!!!
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |