std::thread(线程) 学习记录
1. thread的创建以及面临的问题
1.1 thread.cpp
#include <iostream>
#include <thread>
#include <glog/logging.h>
using namespace std;
void thread1()
{
for(int i = 0; i < 20; ++i)
{
cout<<"thread1..."<<endl;
}
}
void thread2()
{
for(int i = 0; i < 20; ++i)
{
cout<<"thread2..."<<endl;
}
}
int main(int argc, char* argv[])
{
google::InitGoogleLogging(argv[0]);
FLAGS_logtostderr = 1;
FLAGS_colorlogtostderr = 1;
thread th1(thread1);
thread th2(thread2);
LOG(INFO)<<"main...";
return 0;
}
1.2 终端编译
1.3 编译结果
2. thread::join( )
2.1 thread.cpp
#include <iostream>
#include <glog/logging.h>
#include <thread>
using namespace std;
void thread1()
{
for(int i = 0; i < 10; ++i)
{
cout<<"thread1..."<<endl;
}
}
void thread2()
{
for(int i = 0; i < 10; ++i)
{
cout<<"thread2..."<<endl;
}
}
int main(int argc, char* argv[])
{
google::InitGoogleLogging(argv[0]);
FLAGS_logtostderr = 1;
FLAGS_colorlogtostderr = 1;
thread th1(thread1);
thread th2(thread2);
LOG(INFO)<<"********"<<th1.joinable();
th1.join();
LOG(INFO)<<"********"<<th1.joinable();
th2.join();
LOG(WARNING)<<"main...";
return 0;
}
2.2 编译结果
3. thread::detach( )
3.1 thread.cpp
#include <iostream>
#include <glog/logging.h>
#include <thread>
using namespace std;
void thread1()
{
for(int i = 0; i < 10; ++i)
{
cout<<"thread1..."<<endl;
}
}
void thread2()
{
for(int i = 0; i < 10; ++i)
{
cout<<"thread2..."<<endl;
}
}
int main(int argc, char* argv[])
{
google::InitGoogleLogging(argv[0]);
FLAGS_logtostderr = 1;
FLAGS_colorlogtostderr = 1;
thread th1(thread1);
thread th2(thread2);
th1.detach();
th2.detach();
LOG(ERROR)<<"main...";
return 0;
}
3.2 编译结果
4. mutex
mutex是防止不同的线程同时操作同一个共享数据.
4.1 mutex_test.cpp
#include <iostream>
#include <thread>
#include <mutex>
#include <glog/logging.h>
using namespace std;
mutex m;
int cnt = 10;
void thread1()
{
while(cnt > 5)
{
m.lock();
if(cnt > 0)
{
--cnt;
cout<<cnt<<endl;
}
m.unlock();
}
}
void thread2()
{
while(cnt > 0)
{
m.lock();
if(cnt > 0)
{
cnt -= 10;
cout<<cnt<<endl;
}
m.unlock();
}
}
int main(int argc, char* argv[])
{
google::InitGoogleLogging(argv[0]);
FLAGS_logtostderr = 1;
FLAGS_colorlogtostderr = 1;
thread th1(thread1);
thread th2(thread2);
th1.join();
th2.join();
LOG(WARNING)<<"main...";
return 0;
}
4.2 编译结果
- 结果分析:mutex是不安全的,如果当一个线程在解锁之前就异常退出了,那么其他被阻塞的线程就无法进行下去.
5. std::lock_guard
5.1 lock_guard.cpp
使用lock_guard则相对安全,它是基于作用域的,能够自解锁.
#include <iostream>
#include <thread>
#include <mutex>
#include <glog/logging.h>
using namespace std;
mutex m;
int cnt = 10;
void thread1()
{
while(cnt > 5)
{
lock_guard<mutex> lock(m);
if(cnt > 0)
{
--cnt;
cout<<cnt<<endl;
}
}
}
void thread2()
{
while(cnt > 0)
{
lock_guard<mutex> lock(m);
if(cnt > 0)
{
cnt -= 2;
cout<<cnt<<endl;
}
}
}
int main(int argc, char* argv[])
{
google::InitGoogleLogging(argv[0]);
FLAGS_logtostderr = 1;
FLAGS_colorlogtostderr = 1;
thread th1(thread1);
thread th2(thread2);
th1.join();
th2.join();
LOG(WARNING)<<"main...";
return 0;
}
5.2 编译结果