c++多线程
多线程的成员函数以及属性
#include<iostream>
#include<thread>
#include<unistd.h>
using namespace std;
void sayHello(int i,char str[])
{
cout<<"hello thread\t"<<str<<i<<endl;
cout<<"thread id:"<<this_thread::get_id()<<endl;
this_thread::yield();
this_thread::sleep_for(chrono::seconds(1));
}
int main()
{
char *str="zylg";
thread t1(sayHello,1,str);
thread t2([]{cout<<"the world is perfeat\n";});
cout<<"线程的id:"<<t1.get_id()<<"CPU的核心数:"<<t1.hardware_concurrency()<<endl;
t1.join();
t2.join();
return 0;
}
多线程的同步控制
#include<iostream>
#include<thread>
#include<unistd.h>
#include<mutex>
using namespace std;
int total=100;
mutex mu;
void showInt()
{
while(total>0)
{
mu.lock();
cout<<total--<<endl;
mu.unlock();
}
}
int main()
{
thread t1(showInt);
thread t2(showInt);
t1.join();
t2.join();
return 0;
}