#include "iostream"
#include "thread"
#include "string"
#include "functional"
#include "mutex"
using namespace std;
std::mutex glock;
class Th{
public:
Th(){
}
void startThread(){
typedef std::function<void(int,std::string)> FN;
FN fn = [=](int id,std::string name){
volatile int count = 0;
while( (count++) < 5){
glock.lock();
std::cout << "fn: " << ", id=" << id << ", count=" << count << ", name=" << name << std::endl;
glock.unlock();
this_thread::sleep_for(chrono::milliseconds(1000)); //延时1秒
}
};
for (int id = 0; id < 3; id++){
std::string name = "n" + std::to_string(id);
std::thread t(fn,id,name);
t.detach(); //几个线程同时启动,各跑各的
//t.join();//每次只能有一个线程启动。等这个线程全部执行完,再启动执行下一个线程。实际不是多线程
}
}
private:
};
int main(void){
Th th;
th.startThread();
glock.lock();
std::cout << "main end" << std::endl;
glock.unlock();
while(1){
}
return 0;
}
执行结果:
$ ./a.exe
fn: , id=0, count=1, name=n0
fn: , id=1, count=1, name=n1
main end
fn: , id=2, count=1, name=n2
fn: , id=1, count=2, name=n1
fn: , id=0, count=2, name=n0
fn: , id=2, count=2, name=n2
fn: , id=1, count=3, name=n1
fn: , id=2, count=3, name=n2
fn: , id=0, count=3, name=n0
fn: , id=2, count=4, name=n2
fn: , id=1, count=4, name=n1
fn: , id=0, count=4, name=n0
fn: , id=0, count=5, name=n0
fn: , id=1, count=5, name=n1
fn: , id=2, count=5, name=n2