C++多线程基础入门

简要介绍C++多线程编程,希望能为你提供一些启发和帮助。

首先,C++11引入了一个标准库,叫做“并发”(Concurrency)。这个库提供了许多多线程编程的基础工具和算法。它的主要部分是std::thread类,这个类允许您在不同的线程中运行不同的代码。下面是一个用std::thread类创建一个线程的示例:

void myFunction()
{
    // Your code goes here
}
​
int main()
{
    std::thread t(myFunction); // Create a thread to run myFunction
    t.join(); // Wait for thread to finish
    return 0;
}

上述代码首先定义了一个名为myFunction的函数,它将在一个单独的线程中运行,然后在main函数中创建了一个新的线程(即t对象),并将myFunction函数作为参数传递给它。最后,我们调用t.join()来等待线程完成。

除了std::thread类,多线程编程中使用的另一个重要概念是互斥(mutex)。这个概念很重要,因为它可以解决多个线程同时修改同一数据的安全问题。C++11中提供了std::mutex类,您可以使用它来保护共享数据,以确保每个线程单独访问这些数据。下面是一个用std::mutex类保护数据的示例:

#include <mutex>
​
std::mutex g_mutex; // A global mutex to protect shared data
​
void myFunction()
{
    std::lock_guard<std::mutex> lock(g_mutex); // Lock the mutex
​
    // Your code goes here
​
    // The mutex is unlocked when lock goes out of scope
}
​
int main()
{
    std::thread t1(myFunction); // Create a thread to run myFunction
    std::thread t2(myFunction); // Create another thread to run myFunction
    t1.join(); // Wait for t1 to finish
    t2.join(); // Wait for t2 to finish
    return 0;
}

上面的代码使用std::lock_guard类来锁定全局互斥锁g_mutex,然后在myFunction函数中访问共享数据。在std::lock_guard对象超出范围时,mutex自动解锁。这个技术叫做RAII(资源获取即初始化),它能够确保锁定的可靠释放。

最后,还有一个重要的概念叫做条件变量(condition variable)。这个概念可以用于在多个线程之间进行通信,使得某些线程在特定条件下等待,并在条件满足时被唤醒。C++11中提供了std::condition_variable类,它允许您实现这样的逻辑。下面是一个用std::condition_variable类等待特定条件的示例:

#include <mutex>
#include <condition_variable>
​
std::mutex g_mutex; // A global mutex to protect shared data
std::condition_variable g_cond; // A global condition variable to wait for
​
void myFunction()
{
    std::unique_lock<std::mutex> lock(g_mutex); // Lock the mutex
​
    // Wait for a signal from the main thread
    g_cond.wait(lock, []{ return true /* Add your condition here */; });
​
    // Your code goes here
}
​
int main()
{
    std::thread t(myFunction); // Create a thread to run myFunction
​
    // Send a signal to the thread
    {
        std::lock_guard<std::mutex> lock(g_mutex); // Lock the mutex
        // Add code to change the condition that myFunction is waiting for
    }
    g_cond.notify_one(); // Notify the waiting thread
​
    t.join(); // Wait for thread to finish
    return 0;
}

上述代码使用std::condition_variable类来阻塞线程并等待条件,直到满足后被唤醒。通过std::unique_lock类可以实现对互斥锁的上锁和解锁。在main函数中,我们通过g_cond.notify_one()函数发出一个信号,通知正在等待的线程。

本文福利, 免费领取C++学习资料包、技术视频/代码,内容包括(C++基础,网络编程,数据库,中间件,后端开发,音视频开发,Qt开发)↓↓↓↓↓↓见下面↓↓文章底部点击免费领取↓↓

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值