unique_lock 自动解锁

#include <iostream>

#include "mythread.h"
using namespace std;

void mythread::run()
{

while (i < 100)
{
unique_lock<mutex> lock(mtx);
cout << "i=:" << i++ << endl;

}

}

void mythread::start()
{
thread1 = thread(bind(&mythread::run, this));
thread2 = thread(bind(&mythread::run, this));
}
void mythread::fini()
{
thread1.join();
thread2.join();
}

 

#include <thread>
#include <functional>
#include <mutex>
class mythread
{
public:
void start();
void run();
void fini();
mythread()
{
i = 10;
}
private:
std::thread thread1;
std::thread thread2;
int i;
std::mutex mtx;
};

posted @ 2021-08-17 16:50  zzzzhq  阅读(171)  评论(0编辑  收藏  举报