Demo of Thread
苦于每次写就忘的经历,我又写了一个简单的没有质量的Demo,因为太闲了,写完这篇就开始刷题吧
三个文件,People.h
,People.cpp
,main.cpp
。三个文件,两样东西,一个是People的类,一个是main函数调用线程。
People头文件及cpp文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| #pragma once #include <iostream> #include <string> #include <vector> #include <algorithm> #include <Windows.h> #include <stdlib.h> using namespace std;
static int constructTimes = 0; static int copyTimes = 0;
class People { public: People(string str); People(const People &mt);
~People();
void setName(string str); void startWork(int s); void endWork(int e); void calcWorkTime(); private: string m_name; int m_start; int m_end; };
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
| #include "People.h"
People::People(string str) :m_name(str) { constructTimes++; cout << "构造次数:" << constructTimes << endl; } People::People(const People &mt) : m_name(mt.m_name) { copyTimes++; cout << "构造次数:" << copyTimes << endl; } People::~People() { cout << this->m_name << " 调用了析构函数" << endl; }
void People::setName(string str) { cout << "更换岗位开始,需等待片刻" << endl; int i; for (i = 0; i < 3; i++) { Sleep(1000); cout << "更换岗位ing……" << endl; } this->m_name = str;
cout << str << " 设置工作成功,耗时"<< i <<"S" << endl; } void People::startWork(int s) { cout << m_name << " 开始工作,开始时间:" << s << endl; m_start = s; }
void People::endWork(int e) { cout << m_name << " 结束工作,开始时间:" << e << endl; m_end = e; }
void People::calcWorkTime() { cout << m_name << " 的工作时长为:"; cout << m_end - m_start << endl; }
|
主函数文件
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37
| #include <iostream> #include <thread> #include "People.h" class People; using namespace std;
int main(int argc, const char * argv[]) { People p1("aaa"); cout << "线程:" << std::this_thread::get_id() << "开始" << endl; int startTime = 1,endTime; People *p1ptr = &p1; std::thread w1(&People::setName, std::ref(p1ptr), "bbb"); std::thread w2(std::move(w1)); bool w1Joinable = w1.joinable(); cout << "w1的joinable:" << w1Joinable << endl; w2.detach();
cout << "-----------" << endl; p1.startWork(1); for (auto i = 0; i < 5; i++) { Sleep(1000); cout << "工作ing……" << endl; endTime = i; } p1.endWork(endTime); p1.calcWorkTime();
system("pause"); return 0; }
|
输出:
构造次数:1
线程:17668开始
更换岗位开始,需等待片刻w1的joinable:
0
-----------
aaa 开始工作,开始时间:1
工作ing……
更换岗位ing……
更换岗位ing……
工作ing……
更换岗位ing……
bbb 设置工作成功,耗时3S
工作ing……
工作ing……
工作ing……
bbb 结束工作,开始时间:4
bbb 的工作时长为:3
因为是detach()
的方式,因此更换岗位与工作是异步进行的。也就是这是两个单独的线程在进行。