最近在看多线程的东西;
1,第一个就是关于多线程的简单实用,c++11可以支持线程库,vs需要2012版本以上了。那么简单的测试代码如下:
添加了普通的线程之后的代码
#include <thread>
#include <iostream
using namespace std;
void function_1()
{
int m=0;
for (int i = 0;i<10;i++)
{
cout<<"this is another thread !\n";
}
}
void main()
{
thread mythread(function_1);
for (int i = 0; i <10; i++)
{
m_mutex.lock();
cout << "this is mainthread!\n";
m_mutex.unlock();
}
mythread.join();
return;
}
2,为了减少数据竞争,引入线程资源锁mutex
#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
mutex m_mutex;
void function_1()
{
int m=0;
for (int i = 0;i<100;i++)
{
m_mutex.lock();
cout<<"this is another thread !\n";
m_mutex.unlock();
}
}
void main()
{
thread mythread(function_1);
for (int i = 0; i <100; i++)
{
m_mutex.lock();
cout << "this is main thread!\n";
m_mutex.unlock();
}
mythread.join();
return;
}
结果如下:
这里看出结果比较规律,表明线程是按照规律切换执行的。
3,这里存在的一个问题是,如果其中一个线程抛出异常,就会造成死锁,修改成为另外一个(这里面出现一个问题,就是多线程中一个线程抛出异常之后该线程会停止)
#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
mutex m_mutex;
void function_1()
{
try
{
int m=0;
for (int i = 0;i<100;i++)
{
//m_mutex.lock();
lock_guard<std::mutex> guard(m_mutex);
throw "error";
cout<<"this is another thread !\n";
//m_mutex.unlock();
}
}
catch(const char* msg)
{
cout<<msg<<endl;
}
}
void main()
{
try
{
thread mythread(function_1);
//function_1();
for (int i = 0; i <100; i++)
{
m_mutex.lock();
cout << "this is main thread!\n";
m_mutex.unlock();
}
mythread.join();
}
catch(const char* msg )
{
cout<<msg<<endl;
}
return;
}
测试之后,只用到mutex会死锁在一个线程,但是用到另外一个guard就没有问题。而且mutex在调试结束时,会出现debugError的错误;这里出现debugError的原因是,主线程结束,而子线程却没有结束导致的。
4,对资源进行加锁然后封装起来
#include <thread>
#include <iostream>
#include <mutex>
#include <string>
#include <fstream>
using namespace std;
mutex m_mutex;
class LogFile{
public:
LogFile()
{
f.open("log.txt", ifstream::out|fstream::in| ifstream::app);
}
void shared_print(string id,int value)
{
lock_guard<mutex> locker(mut);
if (f.is_open())
{
f<<id<<":"<<value<<endl;
}
}
~LogFile()
{
f.close();
}
private:
fstream f;
mutex mut;
};
void function_1()
{
try
{
int m=0;
for (int i = 0;i<100;i++)
{
m_mutex.lock();
//lock_guard<std::mutex> guard(m_mutex);
throw "error";
cout<<"this is another thread !\n";
m_mutex.unlock();
}
}
catch(const char* msg)
{
cout<<msg<<endl;
}
}
void write_log(LogFile& log)
{
for(int i=0;i>-10000;i--)
{
log.shared_print("child thread",i);
}
}
int main()
{
LogFile logfile;
thread mythread(write_log,std::ref(logfile));
for(int i=0;i<10000;i++)
{
string str = "this is mainthread !";
logfile.shared_print(str,i);
}
mythread.join();
return 0;
}
实际上,在多次运行之后,也并不能完全保证资源的规律性。相比较来说,规律已经比较明显了。