C++ 学习笔记

    技术2022-07-16  71

    文章目录

    std::threadstd::lock_guard&不知名的语法

    std::thread

    线程有两个状态joinable 和detached:

    joinable 表示线程处于活动状态detached 表示线程独立运行 ,但是程序结束时,同程序退出。

    实例程序

    #include<iostream> #include<time.h> #include <thread> #include <unistd.h> #include<sys/time.h> using namespace std; class MCLtest { public: int a; public: MCLtest() { a = 1; } }; int main(void) { int i = 0; std::thread t([&]{ i++; while (1) { printf("1\n"); sleep(1); } } ); if(t.joinable()){ printf("joinable\n"); t.detach(); } // t.join(); sleep(100); return 0; }

    注意事项 当类成员函数使用thread 线程来跑一个类成员函数传递的第一个参数为this 指针。

    实例代码

    void ActionController::StartLooper() { ............... } void ActionController::Run() { ............. std::thread looper{&ActionController::StartLooper, this}; looper.join(); .............. }

    std::lock_guard

    就是一个把封装了的锁,创建是上锁,销毁时解锁。

    实例代码

    #include <thread> #include <mutex> int g_i = 0; std::mutex g_i_mutex; // protects g_i void safe_increment() { std::lock_guard<std::mutex> lock(g_i_mutex); ++g_i; // g_i_mutex is automatically released when lock // goes out of scope } int main() { std::thread t1(safe_increment); std::thread t2(safe_increment); t1.join(); t2.join(); }

    &

    在函数名称前使用& 表示返回值为引用类型。

    未完待续。。。。。。。

    不知名的语法

    // Unsigned int N 表示使用的数据类型,char 表示传入指针的类型,&str 表示传入的指针。N为计算的长度 template <unsigned int N> int printlen(const char(&str)[N]){ return N; } std::string mcl = mps_string("Hello World"); std::cout << mcl << std::endl; 返回结果: 12

    https://my.oschina.net/yangcol/blog/123433 https://en.cppreference.com/w/cpp/thread/thread/joinable

    Processed: 0.012, SQL: 9