首页 > 编程语言 >leetcode & c++多线程刷题日志

leetcode & c++多线程刷题日志

时间:2023-08-29 20:23:00浏览次数:42  
标签:function lock void printFirst c++ sem 多线程 leetcode printSecond

1.按序打印

按序打印
解法

    1. 互斥锁
class Foo {
    mutex mtx1, mtx2;
public:
    Foo() {
        mtx1.lock(), mtx2.lock();
    }

    void first(function<void()> printFirst) {
        printFirst();
        mtx1.unlock();
    }

    void second(function<void()> printSecond) {
        mtx1.lock();
        printSecond();
        mtx1.unlock();
        mtx2.unlock();
    }

    void third(function<void()> printThird) {
        mtx2.lock();
        printThird();
        mtx2.unlock();
    }
};
    1. 条件变量
class Foo {
    condition_variable cv;
    mutex mtx;
    int k = 0;
public:
    void first(function<void()> printFirst) {
        printFirst();
        k = 1;
        cv.notify_all();    // 通知其他所有在等待唤醒队列中的线程
    }

    void second(function<void()> printSecond) {
        unique_lock<mutex> lock(mtx);   // lock mtx
        cv.wait(lock, [this](){ return k == 1; });  // unlock mtx,并阻塞等待唤醒通知,需要满足 k == 1 才能继续运行
        printSecond();
        k = 2;
        cv.notify_one();    // 随机通知一个(unspecified)在等待唤醒队列中的线程
    }

    void third(function<void()> printThird) {
        unique_lock<mutex> lock(mtx);   // lock mtx
        cv.wait(lock, [this](){ return k == 2; });  // unlock mtx,并阻塞等待唤醒通知,需要满足 k == 2 才能继续运行
        printThird();
    }
};
    1. <sempahore.h>
class Foo {
private:
    sem_t sem_1, sem_2;

public:
    Foo() {
        sem_init(&sem_1, 0, 0), sem_init(&sem_2, 0, 0);
    }

    void first(function<void()> printFirst) {
        printFirst();
        sem_post(&sem_1);
    }

    void second(function<void()> printSecond) {
        sem_wait(&sem_1);
        printSecond();
        sem_post(&sem_2);
    }

    void third(function<void()> printThird) {
        sem_wait(&sem_2);
        printThird();
    }
};

    1. std::future 异步操作
class Foo {
    promise<void> pro1, pro2;

public:
    void first(function<void()> printFirst) {
        printFirst();
        pro1.set_value();
    }

    void second(function<void()> printSecond) {
        pro1.get_future().wait();
        printSecond();
        pro2.set_value();
    }

    void third(function<void()> printThird) {
        pro2.get_future().wait();
        printThird();
    }
};


  • 原子操作
class Foo {
    std::atomic<bool> a{ false };
    std::atomic<bool> b{ false };
public:
    void first(function<void()> printFirst) {
        printFirst();
        a = true;
    }

    void second(function<void()> printSecond) {
        while (!a)
            this_thread::sleep_for(chrono::milliseconds(1));
        printSecond();
        b = true;
    }

    void third(function<void()> printThird) {
        while (!b)
            this_thread::sleep_for(chrono::milliseconds(1));
        printThird();
    }
};

2 交替打印 FooBar

交替打印 FooBar
解法

  • <semaphore.h>
#include<semaphore.h>
class FooBar {
private:
    int n;
    sem_t m1, m2;
public:
    FooBar(int n) {
        this->n = n;
        sem_init(&m1, 0, 0);
        sem_init(&m2, 0, 0);
        sem_post(&m2);
    }

    void foo(function<void()> printFoo) {
        
        for (int i = 0; i < n; i++) {
            sem_wait(&m2);
        	// printFoo() outputs "foo". Do not change or remove this line.
        	printFoo();
            sem_post(&m1);
        }
    }

    void bar(function<void()> printBar) {
        
        for (int i = 0; i < n; i++) {
            sem_wait(&m1);
        	// printBar() outputs "bar". Do not change or remove this line.
        	printBar();
            sem_post(&m2);
        }
    }
};

标签:function,lock,void,printFirst,c++,sem,多线程,leetcode,printSecond
From: https://www.cnblogs.com/InsiApple/p/17665747.html

相关文章

  • UE如何制作C++函数事件蓝图
    一.蓝图类中的函数在新建的actor中的C++ .h文件中,声明UFUNCTION(BlueprintCallable,Category="XXXX"),然后在.cpp中写函数的内容即可。编译后用蓝图继承C++类,可以进行函数的调用了二.建立函数库任意蓝图可以调用建立BlueprintFunctionLibrary的C++类,参考一中进行函数......
  • 标准C++ -- day07
    一、虚函数、虚函数表、虚表指针、覆盖1、虚函数在成员函数前面加virtual后,该函数就称为虚函数,此时该类就会像虚进程一样多了一个虚表指针(虚函数表指针,虚指针)classBase{public:voidfunc(void){cout<<"Basefunc"<<endl;}}cout<<size......
  • C++虚函数 覆盖(重写)
    1、虚函数  在成员函数前面加virtual后,该函数就称为虚函数,此时该类就会像虚继承一样多了一个虚表指针(虚函数表指针、虚指针)2、虚函数表  虚表指针指向的是属于该类的一张表格的首地址,该表格中记录了该类中所有虚函数的首地址    如果类中没有其他成员变......
  • 多线程|volatile的使用
    一、内存可见性问题先来看如下代码classMyCounter{publicintflag=0;}publicclassThreadDemo22{publicstaticvoidmain(String[]args){MyCountermyCounter=newMyCounter();Threadt1=newThread(()->{while(myCounter.f......
  • 【Effective C++】定制new和delete
    文章目录一、了解new-handler的行为1、new和malloc的对比2、set_new_handler的使用3、new-handler设计要求4、提供自己的set_new_handler和operatornew5、请记住二、了解new和delete的合理替换时机1、替换编译器提供的operatornew或operatordelete2、请记住三、编写new和delete......
  • Leetcode刷题笔记——单调性
    单调性单调性是数学中使用的一种常见性质,通常用于描述函数,在高等数学中的定义常常为:设函数f(x)在区间I上有定义,如果对于I上的任意两个数x1和x2,当x1<x2时,有f(x1)<f(x2)(或者f(x1)>f(x2)),则称函数f(x)在区间I上是单调递增的(或者单调递减的)。例如如下图像就是两个单调函数。利用单......
  • C++算法
    运行前进行卡夫曼滤波(减小机器检测波动的影响)延迟上机算法速率法原理1、判断最新数据点和前面几个点的差值是否大于设定值2、判断两点间的斜率k是否大于设定值3、判断拟合曲线的符合度是否在规定范围内技术实现///\brief直线拟合-一元回归,拟......
  • c++ 删除 类的拷贝和赋值函数
      #pragmaonce#include"include/cef_app.h"classHttpSchemeFactory:publicCefSchemeHandlerFactory{public:HttpSchemeFactory()=default;//删除拷贝函数HttpSchemeFactory(constHttpSchemeFactory&)=delete;//删除赋值函数H......
  • C++运算符重载
    C语言是没运算符重载的,C++进行了扩充。C++比C语言多了面向对象(类),多了函数重写,运算符重载,实现了(函数重载跟运算符重载都属于编译器静态绑定了地址,所以是静态多态,而虚函数需要在运行期确定,是动态多态)。 如何实现C++跟C语言混合编程?extern"C",其修饰的代码段需要以C语言的方式进......
  • C++11新特性
    文章目录一、关键字及新语法二、STL容器三、多线程四、智能指针五、其他特性一、关键字及新语法列表初始化:inta{10}。auto:自动类型推导。nullptr:空指针。范围for:for(autov:vec)。二、STL容器vector:动态数组。list:双向链表。deque:双端队列。priority_queue:优先队列。map、se......