C++并发编程 -3.同步并发操作

这篇具有很好参考价值的文章主要介绍了C++并发编程 -3.同步并发操作。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

本文介绍如何使用条件变量控制并发的同步操作、C++ 并发三剑客,函数式编程

一.条件变量

1.概念

        C++条件变量(condition variable)是一种多线程编程中常用的同步机制,用于线程间的通信和协调。它允许一个或多个线程等待某个条件的发生,当条件满足时,线程被唤醒并继续执行。

        在C++中,条件变量通常与互斥锁(mutex)一起使用,以确保线程之间的安全访问共享资源。互斥锁用于保护共享资源的访问,而条件变量用于在某个条件满足时通知等待的线程。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

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

void workerThread()
{
    std::unique_lock<std::mutex> lock(mtx);
    while (!isReady)
    {
        cv.wait(lock); // 等待条件变量满足
    }
    std::cout << "Worker thread is awake!" << std::endl;
}

int main()
{
    std::thread worker(workerThread);

    std::this_thread::sleep_for(std::chrono::seconds(2)); // 模拟一些耗时操作

    {
        std::lock_guard<std::mutex> lock(mtx);
        isReady = true;
        cv.notify_one(); // 唤醒等待的线程
    }
    worker.join();
    return 0;
}

        主线程创建了一个工作线程,并在工作线程中等待条件变量isReadytrue。主线程在等待一段时间后,将isReady设置为true,并通过cv.notify_one()唤醒工作线程。工作线程在等待期间调用cv.wait(lock),这会使线程进入等待状态,直到条件变量被唤醒。一旦条件满足,工作线程被唤醒并输出消息。

        其中wait参数有三种使用方式:

wait wait_for wait_until
函数原型 void wait(std::unique_lock<std::mutex>& lock); template< class Rep, class Period > std::cv_status wait_for(std::unique_lock<std::mutex>& lock, const std::chrono::duration<Rep, Period>& rel_time); template< class Clock, class Duration > std::cv_status wait_until(std::unique_lock<std::mutex>& lock, const std::chrono::time_point<Clock, Duration>& abs_time);
功能 调用wait释放锁,等待notify。被唤醒后加锁

1.调用wait释放锁,等待notify。被唤醒后加锁。

2.等待时间超过指定的相对时间,超时后继续加锁。

1.调用wait释放锁,等待notify。被唤醒后加锁。

2.等待时间超过指定的相对时间,无论是否超时仍加锁。

3.等待超过指定时间

返回值

等待时间内被唤醒,则返回std::cv_status::no_timeout;

如果等待时间超时,则返回std::cv_status::timeout

与waitfor一致
示例
cv.wait(lock, []{ return isDataReady; });
cv.wait_for(lock, std::chrono::seconds(5), []{ return isDataReady; }
    auto timeout = std::chrono::steady_clock::now() + std::chrono::seconds(5);
    cv.wait_until(lock, timeout, []{ return isDataReady; })

2.使用条件变量构建线程安全的栈区

        回顾

        在第三章节 -构建线程安全的栈区  为了避免数据竞争,对于pop操作在线程中调用empty判断是否为空,如果不为空,则pop,因为empty和pop内部分别加锁,是两个原子操作,导致pop时可能会因为其他线程提前pop导致队列为空,从而引发崩溃。

void push(T new_value)
{
    std::lock_guard<std::mutex> lock(m);
    data.push(std::move(new_value));
}

T pop()
{
    std::lock_guard<std::mutex> lock(m);
    auto element = data.top();
    data.pop();
    return element;
}

threadsafe_stack1<int> safe_stack;
safe_stack.push(1);
std::thread t1([&safe_stack]() 
{
    if (!safe_stack.empty()) 
    {
       std::this_thread::sleep_for(std::chrono::seconds(1));
       safe_stack.pop();
    }
});
std::thread t2([&safe_stack]() 
{
    if (!safe_stack.empty()) 
    {
        std::this_thread::sleep_for(std::chrono::seconds(1));
        safe_stack.pop();
    }
});

                C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端 

        通过添加《传入引用》或《返回弹出元素的指针》来解决上面异常。但是两种方式都存在一定的弊端:

        传入引用弊端是需要在函数外部构建临时变量影响效率且需要抛出空栈。

        返回智能指针异常下会导致空指针产生。

        这么都不是很友好,所以我们可以通过条件变量完善之前的程序,重新实现一个线程安全队列。

#include <iostream>
#include <thread>
#include <stack>
#include <memory>
#include <mutex>
#include <condition_variable>

using namespace std;

template<typename T>
class threadQueue
{
public:
    threadQueue(): mutx(), condVar(), stackQueue()
    {};
    ~threadQueue(){};

    void push(T value)
    {
        lock_guard<mutex> lk(mutx);
        stackQueue.push(value);
        condVar.notify_one();
    }

    void waitAndpop(T &stackQueue_)
    {
        unique_lock<mutex> lk(mutx);
        /*
           wait函数第二个参数确保队列有数据才进行条件变量后续操作,相当于增加一层判断,更加准确
        */
        condVar.wait(lk, [this](){return !stackQueue.empty();});
        stackQueue_ = stackQueue.top();
        stackQueue.pop();
    }
    shared_ptr<T> waitAndPop()
    {
        unique_lock<mutex> lk(mutx);
        condVar.wait(lk, [this](){return !stackQueue.empty();});
        shared_ptr<T> res = make_shared<T>(stackQueue.top());
        stackQueue.pop();
        return res;
    }

    bool tryPop(T &value)
    {
        lock_guard<mutex> lk(mutx);
            if(stackQueue.empty()){return false;}
        value = stackQueue.top();
        stackQueue.pop();
        return true;
    }
    shared_ptr<T> tryPop()
    {
        lock_guard<mutex> lk(mutx);
        if (stackQueue.empty())
        	return std::shared_ptr<T>();
        shared_ptr<T> res = make_shared<T>(stackQueue.top());
        stackQueue.pop();
        return res;
    }

private:
    mutable mutex mutx;
    condition_variable condVar;
    stack<T> stackQueue;
};

mutex mutxThread;

template<typename T>
void funcProducer(threadQueue<T> &thdQueue)
{
    for(;;)
    {
        for(size_t i = 0; i < __LONG_MAX__; i++)
        {
            thdQueue.push(i);
            lock_guard<mutex> lk(mutxThread);
            cout<<"funcProducer:"<<i<<endl;
            this_thread::sleep_for(chrono::milliseconds(100));
        }
    }
}

template<typename T>
void funcWorker1(threadQueue<T> &thdQueue)
{
    for(;;)
    {
        auto data = thdQueue.waitAndPop();

        lock_guard<mutex> lk(mutxThread);
        cout<<"funcWorker1 waitAndpop:"<<*(data)<<endl;
        // this_thread::sleep_for(chrono::milliseconds(500));
    }
}

template<typename T>
void funcWorker2(threadQueue<T> &thdQueue)
{
    for(;;)
    {
        auto data = thdQueue.tryPop();
        if(data != nullptr)
        {
            lock_guard<mutex> lk(mutxThread);
            cout<<"funcWorker2 waitAndpop:"<<*(data)<<endl;
        }
        // this_thread::sleep_for(chrono::milliseconds(500));
    }
}

int main()
{
    threadQueue<int> thdQueue;

    thread t1(funcProducer<int>, ref(thdQueue));
    thread t2(funcWorker1<int>, ref(thdQueue));
    thread t3(funcWorker2<int>, ref(thdQueue));

    t1.join();
    t2.join();
    t3.join();
}

C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端

二.C++ 并发三剑客

        简单介绍一下future, promise和async三者之间的关系。其具体实现请看本章节第四小节

C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端

1.async

        std::async 是一个用于异步执行函数的模板函数,它返回一个 std::future 对象,该对象用于获取函数的返回值。其主要应用于I/O密集型任务,如网络请求或文件读写,其中操作可能需要等待,但CPU不需要做太多工作.(thread适用于CPU密集型任务)

        async可选填参数:

        指定launch::async:表示任务执行在另一线程。

        指定launch::deferred:表示延迟执行任务,调用get或者wait时才会执行,不会创建线程,惰性执行在当前线程。

        不填写或同时指定:属于未定义行为,编译器会根据实际情况决定采用哪种策略(通常创建线程)

1.1 async异步任务

        async启用异步执行后,在其内部会创建一个线程,任务完成后线程自动销毁,不需要join等操作。


#include <iostream>
#include <thread>
#include <memory>
#include <future>

using namespace std;

void func()
{
    int i = 0;
    for(;;)
    {
        cout<<"func"<<endl;
        this_thread::sleep_for(chrono::seconds(1));
        if(++i == 10) {break;}
    }
    cout<<" thread end"<<endl;
}

int main()
{
    std::future<void> the_answer=std::async(launch::async, func);//deferred

    for(int i = 0; i < 15; ++i)
    {
        cout<<"main run"<<endl;
        this_thread::sleep_for(chrono::seconds(1));
    }

    return 1;
}

  刚运行时可以看到存在两个线程

C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端

  线程退出后:

C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端

1.2 async延时执行

        当指定launch::deferred表示延迟执行任务,调用get或者wait时才会在调用线程中执行。                 std::future::get() 和 std::future::wait() 是 C++ 中用于处理异步任务的两个方法.

1.2.1 future::get()

        这是一个阻塞调用,用于获取 std::future 对象表示的值或异常。如果异步任务还没有完成,get() 会阻塞当前线程,直到任务完成。如果任务已经完成,get() 会立即返回任务的结果。get() 只能调用一次,因为它会移动或消耗掉 std::future 对象的状态。一旦 get() 被调用,std::future 对象就不能再被用来获取结果。如果调用两次,会出现如下结果:

#include <iostream>
#include <thread>
#include <memory>
#include <future>

using namespace std;

void func()
{
    cout<<"func"<<endl;
}

int main()
{
    std::future<void> the_answer=std::async(launch::deferred, func);//deferred

    cout<<"main run"<<endl;
    this_thread::sleep_for(chrono::seconds(1));
    the_answer.get();
    the_answer.get();

    return 1;
}

                C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端 

        为避免多次调用get造成异常,尽量使用wait

1.2.2 future::wait()

        std::future::wait() 也是一个阻塞调用,但它与 get() 的主要区别在于 wait() 不会返回任务的结果。它只是等待异步任务完成。如果任务已经完成,wait() 会立即返回。如果任务还没有完成,wait() 会阻塞当前线程,直到任务完成。与 get() 不同,wait() 可以被多次调用,它不会消耗掉 std::future 对象的状态。

#include <iostream>
#include <thread>
#include <memory>
#include <future>

using namespace std;

int func()
{
    std::this_thread::sleep_for(std::chrono::milliseconds(1000));
    cout<<"func"<<endl;
    return 10;
}

int main()
{
    future<int> the_answer = async(launch::deferred, func);
    cout<<"main run"<<endl;
    
    auto start = std::chrono::high_resolution_clock::now(); 
    the_answer.wait();
    the_answer.wait();
    auto end = std::chrono::high_resolution_clock::now();
    auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start); 
    cout << "the_answer.wait run time: " << duration.count() << " ms" << endl;

    return 1;
}

        C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端 

可以看到只运行了1000ms, 当第一个wait运行结束表示任务执行结束,而第二个wait会立马返回。

wait get
阻塞线程,知道任务运行完毕 阻塞线程,知道任务运行完毕
可多次调用,当任务执行完毕后wait将不在起作用,会立马返回。 不可多次调用,异常
执行任务,不获取结果 执行任务,获取结果
  •  也可以通过wait_for(std::chrono::seconds(0)(要求任务立马返回),判断任务是否已经完成
if (the_answer.wait_for(std::chrono::seconds(0)) == std::future_status::ready)
{
   cout<<"task already over"<<endl;
   return 0;
}
1.3 async使用注意事项
1.3.1 警惕未接受返回值阻塞
#include <iostream>
#include <thread>
#include <memory>
#include <future>

int main()
{
    cout<<"main start"<<endl;
    {
        async(launch::async, [](){
            cout<<"start run async"<<endl;
            this_thread::sleep_for(chrono::milliseconds(1000));
            cout<<"end run async"<<endl;
        });
    }
    cout<<"main end"<<endl;
}

        C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端 

        因为async返回一个右值类型的future,无论左值还是右值,future都要被析构,因为其处于一个局部作用域{}中。 当编译器执行到}时会触发future析构。但是future析构要保证其关联的任务完成,所以需要等待任务完成future才被析构, 所以也就成了串行的效果了。

2.promise和packaged_task

        promise和packaged_task都是C++中的异步编程工具,用于在多线程环境下进行任务的分离和结果的传递。

        promise是一种用于在一个线程中产生结果,并在另一个线程中获取结果的机制。它允许一个线程(称为"提供者")在某个时间点设置一个值或异常,而另一个线程(称为"消费者")在需要时获取该值或异常。

        packaged_task是一种将可调用对象(如函数、函数对象或Lambda表达式)封装为一个可以异步执行的任务的机制。

        两者都是与future结合使用,通过future获取结果或者值。

2.1.future与packaged_task

        packaged_task是一个可调用目标,它包装了一个任务,该任务可以在另一个线程上运行。它可以捕获任务的返回值或异常,并将其存储在future对象中,以便以后使用。

        使用future和packaged_task通常的做法是:

1)  创建一个std::packaged_task对象,该对象包装了要执行的任务。

funciton my_task
packaged_task<int()> task(my_task);

2)  调用packaged_task对象的get_future()方法,该方法返回一个与任务关联的future对象。

future<int> result = task.get_future();

3)  在另一个线程上调用std::packaged_task对象的operator(),以执行任务。

 thread t(move(task));

4)   在需要任务结果的地方,调用与任务关联的future对象的get()方法,以获取任务的返回值或异常。

int value = result.get();

示例:

#include <iostream>
#include <thread>
#include <memory>
#include <future>

using namespace std;

int my_task() {
    this_thread::sleep_for( chrono::seconds(5));
    cout << "my task run 5 s" <<  endl;
    return 42;
}
int main()
{
    // 创建一个包装了任务的  packaged_task 对象  
    packaged_task<int()> task(my_task);
    // 获取与任务关联的  future 对象  
    future<int> result = task.get_future();
    // cout<<"task.get_future()"<<task.get_future().get()<<endl;
    // 在另一个线程上执行任务  
    thread t(move(task));
    t.detach(); // 将线程与主线程分离,以便主线程可以等待任务完成  
    // 等待任务完成并获取结果  
    cout << "will get result"<<endl;
    int value = result.get();
    cout << "The result is: " << value <<  endl;

}

                         C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端

        在上面的示例中,我们创建了一个包装了任务的std::packaged_task对象,并获取了与任务关联的std::future对象。然后,我们在另一个线程上执行任务,并等待任务完成并获取结果。最后,我们输出结果。

2.2.future与promise
2.2.1 设置值

        packaged_task主要是异步过程中任务,promise在异步过程中处理数值。

#include <iostream>
#include <thread>
#include <future>

void set_value(std::promise<int>& prom) {
    std::this_thread::sleep_for(std::chrono::seconds(2));
    // 设置结果为42
    prom.set_value(42);
}

int main() {
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    
    std::thread t(set_value, std::ref(prom));
    // 在主线程中等待结果
    int result = fut.get();
    std::cout << "Result: " << result << std::endl;
    t.join();
    
    return 0;
}

        值得注意的是在调用fut.get()方法时,如果promise的值还没有被设置,则该方法会阻塞当前线程,直到值被设置为止。

2.2.2 设置异常

        promise还有一个set_exception()方法,用于设置异常。该方法接受std::exception_ptr参数,该参数可以通过调用std::current_exception()方法获取。


#include <iostream>
#include <thread>
#include <future>

void set_exception(std::promise<int>& prom) {
    try {
        // 模拟一些可能抛出异常的操作
        throw std::runtime_error("Something went wrong");
    } catch (...) {
        // 捕获异常并设置到 promise 中
        prom.set_exception(std::current_exception());
    }
}

int main() {
    std::promise<int> prom;
    std::future<int> fut = prom.get_future();
    
    std::thread t(set_exception, std::ref(prom));
    
    try {
        // 在主线程中等待结果
        int result = fut.get();
        std::cout << "Result: " << result << std::endl;
    } catch (const std::exception& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }
    
    t.join();
    
    return 0;
}

        set_exception 函数中,我们模拟了一些可能抛出异常的操作,并使用prom.set_exception (std::current_exception()) 将当前捕获的异常设置到 promise 中。在主线程中,我们使用 fut.get() 等待并获取结果。如果在另一个线程中发生了异常,我们可以在主线程中使用 try-catch 块捕获并处理异常。

3 future与shared_future

        当需要多个线程等待同一个执行结果时,需要使用std::shared_future。

        适合使用std::shared_future的场景,多个线程等待同一个异步操作的结果:

#include <iostream>
#include <thread>
#include <future>

void myFunction(std::promise<int>&& promise) 
{
    std::this_thread::sleep_for(std::chrono::seconds(1));
    promise.set_value(42); // 设置 promise 的值
}
void threadFunction(std::shared_future<int> future) 
{
    try {
        int result = future.get();
        std::cout << "Result: " << result<<"this thread id:"<<std::this_thread::get_id() << std::endl;
    }
    catch (const std::future_error& e) {
        std::cout << "Future error: " << e.what() << std::endl;
    }
}
int main() 
{
    std::promise<int> promise;
    std::shared_future<int> future = promise.get_future();
    std::thread myThread1(myFunction, std::move(promise)); // 将 promise 移动到线程中
    // 使用 share() 方法获取新的 shared_future 对象  
    std::thread myThread2(threadFunction, future);
    std::thread myThread3(threadFunction, future);
    myThread1.join();
    myThread2.join();
    myThread3.join();

    return 0;
}

         C++并发编程 -3.同步并发操作,C++,c++,开发语言,linux,服务器,后端

        在这个示例中,创建了一个std::promise<int>对象promise和一个与之关联的std::shared_future<int>对象future。然后,我们将promise对象移动到另一个线程myThread1中,该线程将执行myFunction函数,并在完成后设置promise的值。我们还创建了两个线程myThread2myThread3,它们将等待future对象的结果。如果myThread1成功地设置了promise的值,那么future.get()将返回该值。这些线程可以同时访问和等待future对象的结果,而不会相互干扰。 

4. 自顶向下实现

4.1  用packaged_task实现async

        async异步任务相当于创建线程,不再予以实现。

        async延时执行示例如下:

#include <iostream>
#include <thread>
#include <future>
#include <functional>

using Func = std::function<int(int)>;

std::future<int> myAsync(Func task, int i)
{
    std::packaged_task<int(int)> packaged(task);
    std::future<int> fu = packaged.get_future();

    std::thread t(std::move(packaged), i);
    t.detach();
    return fu;
}

int main()
{
    auto task = [](int i) { std::this_thread::sleep_for(std::chrono::seconds(1)); return i+100; };

    std::future<int> f = myAsync(task, 5);
    std::cout << f.get() << std::endl;
    return 0;
}

         async指定deferred 表示延时进行,其内部与上述内部实现类似,先使用packaged打包需要执行的任务,然后将任务与future绑定,将任务move到线程中,执行完毕后通过future.get获取任务执行结果。如此便满足第二章节图片内容结构。

4.2  使用promise实现packaged_task

          通过promise设置值来完成packaged_task反馈。

#include <iostream>
#include <thread>
#include <future>
#include <functional>

//typename关键字在C++中的主要作用是告诉编译器某个名称是一个类型而不是变量或函数。
template<typename Type, typename... Args>
class myPackTask
{
public:
    myPackTask(std::function<Type(Args...)> _func):func_(_func){}

    std::future<Type> get_future()
    {
        return promise_.get_future();
    }

    void operator()(Args... args)
    {
        Type result = func_(args...);
        promise_.set_value(result);
    }

private:
    std::function<Type(Args...)> func_;
    std::promise<Type> promise_;
};

int add(int a, int b) {
    return a + b;
}

int main() {
    myPackTask<int, int, int> task(add);
    std::future<int> future = task.get_future(); 

    std::thread thread(std::move(task), 2, 3);  
    int result = future.get();  
    std::cout << "Result: " << result << std::endl;

    thread.join();  // 等待线程结束

    return 0;
}
 4.3  实现promise

        其主要思想就是通过条件变量通知get所在线程调用的地方。

#include <iostream>
#include <thread>
#include <mutex>
#include <condition_variable>

template<typename T>
class Promise {
public:
    Promise() : value(nullptr), ready(false) {}

    void set(const T& val) {
        std::unique_lock<std::mutex> lock(mutex);
        value = std::make_shared<T>(val);
        ready = true;
        condition.notify_all();
    }

    T get() {
        std::unique_lock<std::mutex> lock(mutex);
        condition.wait(lock, [this] { return ready; });
        return *value;
    }

private:
    std::shared_ptr<T> value;
    bool ready;
    std::mutex mutex;
    std::condition_variable condition;
};

int main() {
    Promise<int> promise;

    std::thread producer([&promise]() {
        std::this_thread::sleep_for(std::chrono::seconds(2));
        promise.set(42);
    });

    std::thread consumer([&promise]() {
        int result = promise.get();
        std::cout << "Got value: " << result << std::endl;
    });

    producer.join();
    consumer.join();

    return 0;
}

三.并行与函数式编程

以下内容摘自恋恋风尘,博主讲解C++并发非常不错,力荐

1 快速排序

        先使用C++ 设计一个快速排序方法

#include <iostream>
#include <thread>
#include <memory>
#include <future>

template<typename T>
void quick_sort_recursive(T arr[], int start, int end) {
    if (start >= end) return;
    T key = arr[start];
    int left = start, right = end;
    while(left < right) {
        while (arr[right] >= key && left < right) right--;
        while (arr[left] <= key && left < right) left++;
        std::swap(arr[left], arr[right]);
    }
    if (arr[left] < key) {
        std::swap(arr[left], arr[start]);
    }
    quick_sort_recursive(arr, start, left - 1);
    quick_sort_recursive(arr, left + 1, end);
}
template<typename T>
void quick_sort(T arr[], int len) {
    quick_sort_recursive(arr, 0, len - 1);
}

int main() {
    int num_arr[] = { 5,3,7,6,4,1,0,2,9,10,8 };
    int length = sizeof(num_arr) / sizeof(int);
     quick_sort(num_arr, length );
    std::cout << "sorted result is ";
    for (int i = 0; i < length; i++) {
        std::cout << " " << num_arr[i];
    }
    std::cout << std::endl;    
}

2 使用函数式编程快速排序

        函数式编程可以被看作是将函数视为数学中的公式。在函数式编程中,函数被视为一种纯粹的数学映射,它接受输入并产生输出,没有副作用或可变状态。这种思想源于数学中的函数概念,其中函数被定义为将输入映射到输出的关系。

        在第一小节实现快速排序是一种面向过程的编程方式,我们可以通过定义一个函数来实现快速排序算法。这个函数接受一个数组作为输入,并通过一系列的步骤来实现快速排序的逻辑。这些步骤包括选择基准元素、划分数组、递归调用等。

        而使用函数式编程,强调使用纯函数来构建程序,通过函数的组合和转换来处理数据。函数式编程避免使用可变状态和共享状态。

#include <iostream>
#include <thread>
#include <memory>
#include <future>
#include <list>
#include <algorithm>

template<typename T>
std::list<T> sequential_quick_sort(std::list<T> input)
{
    if (input.empty())
    {
        return input;
    }
    std::list<T> result;
    //  ① 将input中的第一个元素放入result中,并且将这第一个元素从input中删除
    result.splice(result.begin(), input, input.begin());  
    //  ② 取result的第一个元素,将来用这个元素做切割,切割input中的列表。
    T const& pivot = *result.begin();    
    //  ③std::partition 是一个标准库函数,用于将容器或数组中的元素按照指定的条件进行分区,
    // 使得满足条件的元素排在不满足条件的元素之前。
    // 所以经过计算divide_point指向的是input中第一个大于等于pivot的元素
        auto divide_point = std::partition(input.begin(), input.end(),
            [&](T const& t) {return t < pivot; });    
    // ④ 我们将小于pivot的元素放入lower_part中
    std::list<T> lower_part;
    lower_part.splice(lower_part.end(), input, input.begin(),
        divide_point);  
    // ⑤我们将lower_part传递给sequential_quick_sort 返回一个新的有序的从小到大的序列
    //lower_part 中都是小于divide_point的值
        auto new_lower(
            sequential_quick_sort(std::move(lower_part)));    
    // ⑥我们剩余的input列表传递给sequential_quick_sort递归调用,input中都是大于divide_point的值。
        auto new_higher(
            sequential_quick_sort(std::move(input)));    
        //⑦到此时new_higher和new_lower都是从小到大排序好的列表
        //将new_higher 拼接到result的尾部
        result.splice(result.end(), new_higher);    
        //将new_lower 拼接到result的头部
        result.splice(result.begin(), new_lower);   
        return result;
}

int main() {
    std::list<int> numlists = { 6,1,0,7,5,2,9,-1 };
    auto sort_result = sequential_quick_sort(numlists);
    std::cout << "sorted result is ";
    for (auto iter = sort_result.begin(); iter != sort_result.end(); iter++) {
        std::cout << " " << (*iter);
    }
    std::cout << std::endl;
}

3 并行处理快速排序

        在快速排序中,我们以某个数字作为基准(一般开头), 分为前半部分和后半部分,然后前半部分和后半部分单独计算。 

        并行排序的思想是将前半部分(或后半部分)单独拷贝一份,置于async中(不指定启动方式,编译器会根据计算次数决定什么时候异步执行什么时候串行),进行并行计算文章来源地址https://www.toymoban.com/news/detail-834591.html

#include <iostream>
#include <thread>
#include <memory>
#include <future>
#include <list>
#include <algorithm>

template<typename T>
std::list<T> parallel_quick_sort(std::list<T> input)
{
    if (input.empty())
    {
        return input;
    }
    std::list<T> result;
    result.splice(result.begin(), input, input.begin());
    T const& pivot = *result.begin();
    auto divide_point = std::partition(input.begin(), input.end(),
        [&](T const& t) {return t < pivot; });
    std::list<T> lower_part;
    lower_part.splice(lower_part.end(), input, input.begin(),
        divide_point);
    // ①因为lower_part是副本,所以并行操作不会引发逻辑错误,这里可以启动future做排序
    std::future<std::list<T>> new_lower(
        std::async(&parallel_quick_sort<T>, std::move(lower_part)));
    // ②
    auto new_higher(
        parallel_quick_sort(std::move(input)));    
        result.splice(result.end(), new_higher);    
        result.splice(result.begin(), new_lower.get());    
        return result;
}

int main() 
{
    std::list<int> numlists = { 6,1,0,7,5,2,9,-1 };
    auto sort_result = parallel_quick_sort(numlists);
    std::cout << "sorted result is ";
    for (auto iter = sort_result.begin(); iter != sort_result.end(); iter++) {
        std::cout << " " << (*iter);
    }
    std::cout << std::endl;
}

到了这里,关于C++并发编程 -3.同步并发操作的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 基于linux下的高并发服务器开发(第一章)- 目录操作函数

     (1)int mkdir(const char* pathname,mode_t mode); #include sys/stat.h #include sys/types.h int mkdir(const char *pathname, mode_t mode);     作用:创建一个目录     参数:          pathname: 创建的目录的路径         mode: 权限,八进制的数     返回值:          成功返回0, 失败返回-1  (

    2024年02月16日
    浏览(33)
  • C++并发操作解密:轻松搞定数据同步

      概述: 在C++中,通过互斥锁解决并发数据同步问题。定义共享数据和互斥锁,编写线程函数,使用互斥锁确保操作的原子性。主函数中创建并启动线程,保障线程安全。实例源代码演示了简单而有效的同步机制。 在C++中解决并发操作时的数据同步问题通常需要使用互斥锁

    2024年02月04日
    浏览(23)
  • linux并发服务器 —— linux网络编程(七)

    C/S结构 - 客户机/服务器;采用两层结构,服务器负责数据的管理,客户机负责完成与用户的交互;C/S结构中,服务器 - 后台服务,客户机 - 前台功能; 优点 1. 充分发挥客户端PC处理能力,先在客户端处理再提交服务器,响应速度快; 2. 操作界面好看,满足个性化需求; 3.

    2024年02月09日
    浏览(59)
  • C++并发编程 | 原子操作std::atomic

    目录 1、原子操作std::atomic相关概念 2、不加锁情况 3、加锁情况  4、原子操作 5、总结 原子操作: 更小的代码片段,并且该片段必定是连续执行的,不可分割。 1.1 原子操作std::atomic与互斥量的区别 1) 互斥量 :类模板,保护一段共享代码段,可以是一段代码,也可以是一个

    2023年04月26日
    浏览(27)
  • Linux学习之网络编程3(高并发服务器)

    Linux网络编程我是看视频学的,Linux网络编程,看完这个视频大概网络编程的基础差不多就掌握了。这个系列是我看这个Linux网络编程视频写的笔记总结。 问题: 根据上一个笔记,我们可以写出一个简单的服务端和客户端通信,但是我们发现一个问题——服务器只能连接一个

    2024年02月01日
    浏览(32)
  • Linux网络编程:多进程 多线程_并发服务器

    文章目录: 一:wrap常用函数封装 wrap.h  wrap.c server.c封装实现 client.c封装实现 二:多进程process并发服务器 server.c服务器 实现思路 代码逻辑  client.c客户端 三:多线程thread并发服务器 server.c服务器 实现思路 代码逻辑  client.c客户端 ​​​​   read 函数的返回值 wrap.h  wrap

    2024年02月12日
    浏览(42)
  • 多进程并发TCP服务器模型(含客户端)(网络编程 C语言实现)

    摘要 :大家都知道不同pc间的通信需要用到套接字sockte来实现,但是服务器一次只能收到一个客户端发来的消息,所以为了能让服务器可以接收多个客户端的连接与消息的传递,我们就引入了多进程并发这样一个概念。听名字就可以知道--需要用到进程,当然也有多线程并发

    2024年02月17日
    浏览(40)
  • 【Linux网络编程】高并发服务器框架 线程池介绍+线程池封装

    前言 一、线程池介绍 💻线程池基本概念 💻线程池组成部分 💻线程池工作原理  二、线程池代码封装 🌈main.cpp 🌈ThreadPool.h 🌈ThreadPool.cpp 🌈ChildTask.h  🌈ChildTask.cpp 🌈BaseTask.h 🌈BaseTask.cpp 三、测试效果 四、总结 📌创建线程池的好处 本文主要学习 Linux内核编程 ,结合

    2024年01月16日
    浏览(74)
  • 【Linux】C++项目实战-高并发服务器详析

    橙色 server_process.c文件内容如下: 注意第70行的if(errno == EINTR),如果没有这个if判断的话,当同时多个客户端链接进来,停掉一个客户端,然后再启动一个客户端,就会发现没法连接了,accept会报一个错误。因为一个客户端停掉,在服务器端就相当于一个子进程终止执行,会发

    2024年02月09日
    浏览(38)
  • 【Linux网络编程】TCP并发服务器的实现(IO多路复用select)

    服务器模型主要分为两种, 循环服务器 和 并发服务器 。 循环服务器 : 在同一时间只能处理一个客户端的请求。 并发服务器 : 在同一时间内能同时处理多个客户端的请求。 TCP的服务器默认的就是一个循环服务器,原因是有两个阻塞 accept函数 和recv函数 之间会相互影响。

    2024年02月03日
    浏览(61)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包