美文网首页
c++11 std::thread使用总结

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

作者: 剑有偏锋 | 来源:发表于2020-01-02 18:24 被阅读0次

代码

#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

相关文章

网友评论

      本文标题:c++11 std::thread使用总结

      本文链接:https://www.haomeiwen.com/subject/cfpooctx.html