2 Star 5 Fork 1

beth/ConcurrencySample

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
thread_3.cpp 1.96 KB
一键复制 编辑 原始数据 按行查看 历史
beth 提交于 2021-02-07 11:52 . Submit sample code.
/**
* @file thread_3.cpp
* @brief ݲ
*/
#include <iostream>
#include <thread>
using namespace std;
class Widget
{
public:
mutable int v = 0;
Widget() : v(0) { cout << "Widget(), thread id = " << this_thread::get_id() << endl; }
Widget(int i) : v(i) { cout << "Widget(int i), thread id = " << this_thread::get_id() << endl; }
Widget(const Widget& w) : v(w.v) { cout << "Widget(const Widget& w), thread id = " << this_thread::get_id() << endl; }
Widget(Widget&& w) noexcept {
v = w.v;
cout << "Widget(Widget&& w), thread id = " << this_thread::get_id() << endl;
}
void func(const string& s) { cout << "void func(string& s), thread id = " << std::this_thread::get_id() << endl; }
};
void fun(const Widget& w) {
this_thread::sleep_for(chrono::milliseconds(1000));
cout << "thread id = " << this_thread::get_id() << " begin." << endl;
cout << "w.v = " << ++w.v << endl;
cout << "thread id = " << this_thread::get_id() << " endl." << endl;
}
void implicit(const Widget& w)
{
cout << "implicit, thread id =" << std::this_thread::get_id() << endl;
}
int main()
{
cout << "main thread id = " << this_thread::get_id() << " begin." << endl;
Widget w;
cout << "----------------------- thread 1 ----------------------- " << endl;
thread t1(fun, w);
t1.join();
cout << "after thread w.v = " << w.v << endl;
cout << "----------------------- thread 2 ----------------------- " << endl;
thread t2(fun, ref(w));
t2.join();
cout << "after thread w.v = " << w.v << endl;
cout << "----------------------- thread 3 ----------------------- " << endl;
const char* name = "asdf";
thread t3(&Widget::func, &w, name);
t3.detach();
cout << "----------------------- thread 4 ----------------------- " << endl;
thread t4(&Widget::func, &w, string(name));
t4.join();
cout << "----------------------- thread 5 ----------------------- " << endl;
thread t5(implicit, 1);
t5.join();
cout << endl << "main thread id = " << this_thread::get_id() << " end." << endl;
return 0;
}
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C++
1
https://gitee.com/bethjohanssen/concurrency-sample.git
git@gitee.com:bethjohanssen/concurrency-sample.git
bethjohanssen
concurrency-sample
ConcurrencySample
master

搜索帮助

0d507c66 1850385 C8b1a773 1850385