温馨提示×

从C++ Cookbook学习多线程编程

c++
小樊
83
2024-08-29 19:02:59
栏目: 编程语言

《C++ Cookbook》是一本关于C++编程的实用教程,其中包含了许多关于多线程编程的示例和解释

  1. 包含头文件:在使用C++的线程库之前,需要包含<thread>头文件。
#include<iostream>
#include<thread>
  1. 创建线程:使用std::thread类创建一个新线程。将要执行的函数作为参数传递给std::thread对象。
void myFunction() {
    // 在这里执行你的任务
}

int main() {
    std::thread t(myFunction); // 创建一个新线程并执行myFunction
    t.join(); // 等待线程完成
    return 0;
}
  1. 传递参数给线程函数:如果你的函数需要参数,可以在创建std::thread对象时传递这些参数。
void myFunctionWithArgs(int a, int b) {
    // 在这里执行你的任务
}

int main() {
    std::thread t(myFunctionWithArgs, 10, 20); // 创建一个新线程并执行myFunctionWithArgs
    t.join(); // 等待线程完成
    return 0;
}
  1. 线程同步:当多个线程需要访问共享资源时,需要使用互斥锁(std::mutex)来确保同一时间只有一个线程可以访问资源。
#include <mutex>

std::mutex mtx; // 全局互斥锁

void threadFunction() {
    mtx.lock(); // 加锁
    // 访问共享资源
    mtx.unlock(); // 解锁
}

int main() {
    std::thread t1(threadFunction);
    std::thread t2(threadFunction);
    t1.join();
    t2.join();
    return 0;
}
  1. 使用std::unique_lock简化互斥锁的使用:std::unique_lock可以自动管理互斥锁的加锁和解锁操作,从而简化代码。
#include <mutex>

std::mutex mtx; // 全局互斥锁

void threadFunction() {
    std::unique_lock<std::mutex> lock(mtx); // 自动加锁
    // 访问共享资源
    // 自动解锁
}

int main() {
    std::thread t1(threadFunction);
    std::thread t2(threadFunction);
    t1.join();
    t2.join();
    return 0;
}
  1. 使用条件变量(std::condition_variable)实现线程间的同步:条件变量允许一个或多个线程等待,直到另一个线程通知它们。
#include<condition_variable>

std::mutex mtx;
std::condition_variable cv;
bool ready = false;

void print_id() {
    std::unique_lock<std::mutex> lck(mtx);
    while (!ready) { // 如果ready为false,则等待
        cv.wait(lck); // 当前线程被阻塞,等待条件变量被通知
    }
    // 打印线程ID
    std::cout << "thread "<< std::this_thread::get_id() << '\n';
}

void go() {
    std::unique_lock<std::mutex> lck(mtx);
    ready = true; // 修改共享变量
    cv.notify_all(); // 通知所有等待的线程
}

int main() {
    std::thread threads[10];
    for (auto& th : threads) {
        th = std::thread(print_id);
    }

    std::cout << "10 threads ready to race...\n";
    go(); // 启动竞争

    for (auto& th : threads) {
        th.join();
    }

    return 0;
}

这些示例仅涵盖了C++多线程编程的基本概念。在实际应用中,你可能还需要处理更复杂的场景,如线程池、原子操作、锁无关编程等。建议你深入研究C++标准库中的线程支持,以便更好地理解和应用多线程编程。

0