本文是学习了 Guancheng 大神的文章后,根据文中的相关问题,进行代码分析,并且总结出这篇博客。
原文地址:http://blog.youkuaiyun.com/freeelinux/article/details/54091140
大神文章地址:http://www.parallellabs.com/2011/10/02/lock-in-parallel-programming/#comment-1245。
在并行程序中,锁的使用主要会引发两类难题,一类是诸如死锁、活锁等引起的多线程 bug;另一类是由锁竞争引起的性能瓶颈。本文的分析主要是大神的分析,中间穿插我的验证以及总结,可以说是一篇 ”读博笔记“,可以直接点上方链接看原文。
1.用锁来防止 Data Race
#include <pthread.h>
int counter = 0;
void *func(void *params)
{
counter++; //数据竞跑
}
void main()
{
pthread_t thread1, thread2;
pthread_create(&thread1, 0, func, 0);
pthread_create(&thread2, 0, func, 0);
pthread_join(thread1, 0 );
pthread_join(thread2, 0 );
}
load [%counter], rax; // 线程1从counter读取0到寄存器rax
add rax, 1; // 线程1对寄存器rax进行加1
load [%counter], rbx; // 线程2从counter读取0到寄存器rbx
store rax [%counter]; // 线程1把1写入counter的主存地址
add rbx, 1; // 线程2对寄存器rbx进行加1
store rbx, [%counter]; // 线程2把1写入counter的主存地址为了防止例1中的数据竞跑现象,我们可以使用锁来保证每个线程对counter++操作的独占访问(即保证该操作是原子的)。在例3的程序中,我们使用mutex锁将counter++操作放入临界区中,这样同一时刻只有获取锁的线程能访问该临界区,保证了counter++的原子性:即只有在线程1执行完counter++的三条指令之后线程2才能执行counter++操作,保证了counter的最终值必定为2。
#include <iostream>
#include <thread>
#include <mutex>
#include <vector>
#include <algorithm>
int counter = 0;
std::mutex mt;
void thread_task()
{
// mt.lock();
for(int i=0; i<1000; ++i)
counter++;
// mt.unlock();
}
int main()
{
std::vector<std::thread> workers;
for(int i=0; i<5; ++i){
auto t = std::thread(thread_task);
workers.push_back(std::move(t));
}
std::for_each(workers.begin(), workers.end(), std::mem_fn(&std::thread::join));
std::cout<<counter<<std::endl;
return 0;
}
375



被折叠的 条评论
为什么被折叠?



