Commit 48b5a4cc authored by Administrator's avatar Administrator
Browse files

add thread

parent f0334279
#include <iostream>
#include <thread>
using namespace std;
// 定义用于用法1的函数
void foo(int tid, string name) {
string msg;
msg = "Thread " + to_string(tid) + " starting\n";
cout << msg;
for (int i = 0; i < 10; i++) {
msg = "Hello from foo " + to_string(tid) + ":"
+ name + ":" + to_string(i) + " ending\n";
cout << msg;
}
msg = "Thread " + to_string(tid) + " ending\n";
cout << msg;
};
// 定义用于用法2的函数对象
class func_obj_class {
public:
// ()操作符重载
void operator() (int tid, string name) {
string msg;
msg = "Thread " + to_string(tid) + " starting\n";
cout << msg;
for (int i = 0; i < 10; i++) {
msg = "Hello from func_obj_class " + to_string(tid) + ":"
+ name + ":" + to_string(i) + " ending\n";
cout << msg;
}
msg = "Thread " + to_string(tid) + " ending\n";
cout << msg;
}
};
int main () {
cout << thread::hardware_concurrency() << endl;
// 用法1: 通过指定函数名(函数指针),启动线程
thread func_t0(foo, 0, "first");
thread func_t1(foo, 1, "second");
// 用法2: 通过指定函数对象,启动线程
thread obj_t0(func_obj_class(), 2, "third");
// 用法3: 通过Lambda表达式,启动线程
// 定义Lambda表达式
auto f = [] (int tid, string name) {
string msg;
msg = "Thread " + to_string(tid) + " starting\n";
cout << msg;
for (int i = 0; i < 10; i++) {
msg = "Hello from auto_f " + to_string(tid) + ":"
+ name + ":" + to_string(i) + " ending\n";
cout << msg;
}
msg = "Thread " + to_string(tid) + " ending\n";
cout << msg;
};
// 使用Lambda表达式启动线程
thread auto_f_t0(f, 3, "fourth");
// 等待所有线程结束
func_t0.join();
func_t1.join();
obj_t0.join();
auto_f_t0.join();
cout << "main() exiting" << endl;
}
\ No newline at end of file
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment