c++11 std::thread使用总结

代码

#include <iostream>
#include <thread>

void foo()
{
    std::cout<<"in foo \n";
}

void bar(int x) 
{
    std::cout<<"in bar"<<x<<std::endl;
}

int main() 
{
    std::thread first(foo);
    std::thread second(bar, 99);

    first.join();
    second.detach();

    std::cout<<"end of main\n";

    return 0;
}

编译

 g++   -std=c++11 -pthread -o threadtest threadtest.cpp

输出

li@ubuntu:~/testc11$ ./threadtest 
in foo 
in bar99
end of main
li@ubuntu:~/testc11$ 
li@ubuntu:~/testc11$ ./threadtest 
in foo 
end of main
li@ubuntu:~/testc11$ ./threadtest 
in foo 
in bar99
end of main
li@ubuntu:~/testc11$ ./threadtest 
in foo 
in barend of main

总结

1 join()主线程等待子线程结束方可执行下一步(串行),
detach()是的子线程放飞自我,独立于主线程并发执行,主线程后续代码段无需等待。

2 在类内部创建线程,创建线程所在函数和传参的函数都要为static


image.png

遇到的问题

undefined reference to `pthread_create'
=》解决,编译带 -pthread 参数

引用

http://www.cplusplus.com/reference/thread/thread/?kw=thread

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