c++11特性之std::thread

std::thread 在 #include<thread> 头文件中声明,因此使用 std::thread 时需要包含 #include<thread> 头文件

最后总结下std::thread对比于pthread的优缺点:
优点:

  1. 简单,易用
  2. 跨平台,pthread只能用在POSIX系统上(其他系统有其独立的thread实现)
  3. 提供了更多高级功能,比如future
  4. 更加C++(跟匿名函数,std::bind,RAII等C++特性更好的集成)

缺点:

  1. 没有RWlock。有一个类似的shared_mutex,不过它属于C++14,你的编译器很有可能不支持。
  2. 操作线程和Mutex等的API较少。毕竟为了跨平台,只能选取各原生实现的子集。如果你需要设置某些属性,需要通过API调用返回原生平台上的对应对象,再对返回的对象进行操作

以下是一个常规使用方法:
CTime.cpp

#include <iostream>
#include <thread>

class CTimer {
public:
    // 析构函数
    virtual ~CTimer() {

    }
    // 开始
    void start()
    {
        t = new std::thread(&CTimer::run, this);
    }

    void run()
    {
        std::cout << "Main thread!\n";
        std::this_thread::sleep_for(std::chrono::seconds(1));

        //stop();
        return;
    }

    // 结束
    void stop()
    {
        if (t->joinable())
        {
            t->join();
        }
    }
private:
    std::thread *t;
};
int main()
{
    std::cout << "Hello World!\n";
    CTimer time_test;
    time_test.start();
    time_test.stop();
    system("pause");
}

关注一些报错:

 Test::fun()
  {
     ... ...
     
      std::thread t1( &class::run, this);
  }

比如这样的一段简单代码,会报错,这是因为t1 在方法执行完后,会析构

另外跨线程使用一些变量的时候,也会出现一些报错。还有就是,释放,比如time_test 释放的时候,需要先join一下,才能线程安全的释放。
After a call to this function, the thread object becomes non-joinable and can be destroyed safely.

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容