Last active
December 12, 2015 00:59
-
-
Save chenshuo/4688011 to your computer and use it in GitHub Desktop.
Show why lock is needed for reading/writing one shared_ptr from two threads simultaneously.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <muduo/base/Mutex.h> | |
#include <muduo/base/Thread.h> | |
#include <boost/shared_ptr.hpp> | |
#include <stdio.h> | |
boost::shared_ptr<int> g; | |
muduo::MutexLock mutex; | |
void read_g() | |
{ | |
boost::shared_ptr<int> x; | |
long sum = 0; | |
for (int i = 0; i < 1000 * 1000; ++i) | |
{ | |
x.reset(); | |
{ | |
// muduo::MutexLockGuard lock(mutex); | |
x = g; | |
} | |
sum += *x; | |
} | |
printf("sum = %ld\n", sum); | |
} | |
void write_g() | |
{ | |
for (int i = 0; i < 1000 * 1000; ++i) | |
{ | |
boost::shared_ptr<int> n(new int(42)); | |
{ | |
// muduo::MutexLockGuard lock(mutex); | |
g = n; | |
} | |
} | |
} | |
int main() | |
{ | |
g.reset(new int(42)); | |
muduo::Thread t1(read_g); | |
muduo::Thread t2(write_g); | |
t1.start(); | |
t2.start(); | |
t1.join(); | |
t2.join(); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <memory> | |
#include <mutex> | |
#include <thread> | |
std::shared_ptr<int> g; | |
std::mutex mutex; | |
void read_g() | |
{ | |
std::shared_ptr<int> x; | |
long sum = 0; | |
for (int i = 0; i < 1000 * 1000; ++i) | |
{ | |
x.reset(); | |
{ | |
// std::lock_guard<std::mutex> guard(mutex); | |
x = g; | |
} | |
sum += *x; | |
} | |
printf("sum = %ld\n", sum); | |
} | |
void write_g() | |
{ | |
for (int i = 0; i < 1000 * 1000; ++i) | |
{ | |
std::shared_ptr<int> n(new int(42)); | |
{ | |
// std::lock_guard<std::mutex> guard(mutex); | |
g = n; | |
} | |
} | |
} | |
int main() | |
{ | |
g.reset(new int(42)); | |
std::thread t1(read_g); | |
std::thread t2(write_g); | |
t1.join(); | |
t2.join(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment