join()和detach()
#include "pch.h"
#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <sstream>
#include <ctime>
#include <iomanip>
using namespace std;
void print_time() {
auto now = chrono::system_clock::now();
time_t in_time_t = chrono::system_clock::to_time_t(now);
struct tm *in_time = new tm();
localtime_s(in_time, &in_time_t);
std::stringstream ss;
ss << put_time(in_time, "%Y-%m-%d %X");
cout << "now is: " << ss.str() << endl;
}
void sleep_thread() {
this_thread::sleep_for(chrono::seconds(5)); //沉睡5秒
cout << "[thread-" << this_thread::get_id() << "] is waking up" << endl;
}
void loop_thread() {
for (int i = 0; i < 10; i++) {
cout << "[thread-" << this_thread::get_id() << "] print: " << i << endl;
}
}
int main()
{
print_time();
thread t1(sleep_thread);
thread t2(loop_thread);
t1.join(); //等待线程完成
t2.detach(); //允许线程独立执行
print_time();
return 0; //程序等待线程t1完成后结束,一共运行5秒
}
call_once和once_flag
#include "pch.h"
#include <iostream>
#include <thread>
#include <string>
#include <mutex>
using namespace std;
void init() {
cout << "Initialing..." << endl; //只会被执行一次
}
void worker(once_flag* flag) {
call_once(*flag, init);
}
int main() {
once_flag flag;
thread t1(worker, &flag);
thread t2(worker, &flag);
thread t3(worker, &flag);
t1.join();
t2.join();
t3.join();
return 0;
}
并发
#include "pch.h"
#include <iostream>
#include <thread>
#include <string>
#include <mutex>
#include <vector>
using namespace std;
static double sum = 0;
static mutex exclusive;
void concurrent_worker(int min, int max) {
double now_sum = 0;
for (int i = min; i <= max; i++) {
now_sum += pow(i,2);
}
exclusive.lock();
sum += now_sum;
exclusive.unlock(); //只在写的时候加锁,降低锁的粒度,把耗时运算放在外面
}
void concurrent_task(int min,int max) {
auto start_time = chrono::steady_clock::now();
unsigned concurrent_count = thread::hardware_concurrency(); //获取硬件真正能并行运行的任务数量
cout << "hardware_concurrency: " << concurrent_count << endl;
vector<thread> threads;
for (int t = 0; t < concurrent_count; t++) {
int range = max / concurrent_count * (t + 1);
threads.push_back(thread(concurrent_worker, min, range));
min = range + 1;
}
for (int i = 0; i < threads.size(); i++) {
threads[i].join();
}
auto end_time = chrono::steady_clock::now();
auto ms = chrono::duration_cast<chrono::milliseconds>(end_time - start_time).count();
cout << "Concurrent task finish, " << ms << " ms consumed, Result: " << sum << endl;
}
int main() {
concurrent_task(0,4);
}