C++多线程
1.新建文件夹multi_thread
2.cd multi_thread
3.新建CMakeFiles.txt
cmake_minimum_required(VERSION 3.20)
project(multi_thread)
set(CMAKE_CXX_STANDARD 11)
add_executable(thread main.cpp)
4.新建main.cpp
#include<bits/stdc++.h>
#include<thread>
#include<mutex>
using namespace std;
mutex mu_;
int global;
void callback(int i)
{
cout<<"this is thread "<<i<<endl;
unique_lock<mutex>lock(mu_);//全局变量加锁,防止多线程干扰
global+=20;
lock.unlock();
}
int main(int argc,const char** argv)
{
cout<<"hello world"<<endl;
vector<int>g;
vector<thread>thread_list{};//用vector创建多线程
for(int i=1;i<=10;i++)
{
//std::ref(g)
thread_list.push_back(thread (callback,i));
}
for(int i=1;i<=10;i++)
{
thread_list[i-1].join();//结束多线程
}
cout<<global<<endl;
// thread t1(callback,1);
// t1.join();
return 0;
}
5.编译运行
cd multi_thread
cmake .
make
./thread