Data 1028/11/06 Add By WJB
这次说一下多线程中的数据竞争和互斥对象,因为多线程中每个线程是独立工作的,经常会遇到多个线程使用一个对象,这样就造成数据竞争,所以在多线程中处理数据竞争问题也是很重要的。
1,简单示例,没有做互斥处理
#include <thread>
#include <iostream>
using namespace std;
void Function_1()
{
for (int i = 0; i < 100; i++)
{
cout << "my name is multithread!\n";
}
}
int main()
{
thread mythread(Function_1);
for (int i = 0; i <100; i++)
{
cout << "this is mainthread!\n";
}
mythread.join(); //阻塞式
return 0;
}
输出结果如下,没有任何规律
2,lock()和Unlock()
在上述代码中cout是一个全部变量,在主线程和子线程中被同事调用,并且没有做任何互斥处理,导致两个线程抢夺该资源,为了放着线程抢夺资源,对资源加入锁(Mutex);
#include <thread>
#include <iostream>
#include <mutex>
using namespace std;
mutex m_mutex;
void Function_1()
{
for (int i = 0; i < 100; i++)
{
m_mutex.lock();
cout << "my name is multithread!\n";
m_mutex.unlock();
}
}
int main()
{
thread mythread(Function_1);
for (int i = 0; i <100; i++)
{
m_mutex.lock();
cout << "this is mainthread!\n";
m_mutex.lock();
}
mythread.join(); //阻塞式
return 0;
}
资源被使用时,对资源加上锁,这样资源就不会被其他线程使用,必须等解锁后才能被其他线程调用。再看数据结果就是规律输出了,(这个输出结果跟电脑性能有关系,高性能的规律性比较强)。
3,lock_gard
在上述代码print_string()中,如果std::cout << smg << endl 抛出异常,则线程被锁死。所以需要改进,使用lock_gard;代码如下:
void print_string(string& smg )
{
//m_mutex.lock();
std::lock_guard<std::mutex> guard(m_mutex);
std::cout << smg << endl;
//m_mutex.unlock();
}
4,资源保护
在上述代码中,std::cout是一个全局变量,可以被所有类拿到,所以无法被真正保护起来。对需要加锁的资源进行封装。代码如下:
#include <thread>
#include <iostream>
#include <string>
#include <mutex>
#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)
{
std::lock_guard<mutex> locker(mut);
if (f.is_open())
{
f << id << ":" << value<<endl;
}
}
private:
fstream f;
mutex mut;
};
void wright_log(LogFile& log )
{
for (int i=0;i>-100;i--)
{
log.shared_print("child thread", i);
}
}
int main()
{
LogFile logfile;
thread mythread(wright_log, std::ref(logfile));
for (int i = 0; i <100; i++)
{
string str = "this is mainthread!";
logfile.shared_print(str, i);
}
mythread.join(); //阻塞式
return 0;
}
这样两个线程向同一个文件中写入不会发生冲突。
上一篇文章链接:https://blog.csdn.net/wangjianbo09/article/details/83758791