c++多线程の数据竞争和互斥对象

时间:2023-12-16 18:19:26

看两个代码:

void function()
{ for(int i=;i>;i--)
{
cout<<"from sub thread"+i<<endl;
}
} void main()
{
thread((function()));
for(int i=;i<;i++)
{
cout<<"from main thread"+i<<endl;
} }

以上由于共用资源cout对象,而出现不规律的输出;

可以通过加入mutex对象进行加锁,需要包含头文件mutex.h

nutex mu;
void shared_printf(string fromThread,int id)
{ mu.lock();
cout<<fromThread+id<<end;
mu.unlock(); }
存在风险是cout中抛出异常将永远锁死;
这时候可以用对象:std::mutex_gard<std::mutex> gard(mu);
对象,无论cout是否成功,都将自动解锁;
具体如下:
nutex mu;
void shared_printf(string fromThread,int id)
{
std::mutex_gard<std::mutex> gard(mu);
cout<<fromThread+id<<end; } 但是以上的代码只保证了在此程序中的互斥,锁并没有完全保护住cout,存在一定的不安全性;以上问题可以通过新建立一个类,私有调用保护;

注意:线程的安全永远是相对的,根据需要控制安全级别