Created
February 21, 2015 00:16
-
-
Save pec1985/2ce4f9b387aee057d07f to your computer and use it in GitHub Desktop.
Usage of std::mutex
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 <thread> | |
#include <memory> | |
#include <mutex> | |
#include <iostream> | |
#include <vector> | |
#define USE_MUTEX 1 | |
class Foo | |
{ | |
public: | |
Foo(){}; | |
double read(){ | |
m_mutex.lock(); | |
std::cout << "read" << m_foo << std::endl; | |
auto val = m_foo; | |
m_mutex.unlock(); | |
return val; | |
}; | |
void write(double meh) { | |
m_mutex.lock(); | |
std::cout << "write" << m_foo << std::endl; | |
m_foo = meh; | |
m_mutex.unlock(); | |
}; | |
double readNoMutex() | |
{ | |
std::cout << "read" << m_foo << std::endl; | |
return m_foo; | |
} | |
void writeNoMutex(double meh) | |
{ | |
std::cout << "write" << m_foo << std::endl; | |
m_foo = meh; | |
} | |
private: | |
double m_foo {0.0}; | |
std::mutex m_mutex; | |
}; | |
int main() { | |
auto foo = new Foo(); | |
std::vector<std::thread*> all_threads; | |
for(int i = 0; i < 10; i++) { | |
all_threads.push_back(new std::thread([=]{ | |
#if USE_MUTEX | |
foo->write(12.12 + i); | |
foo->read(); | |
#else | |
foo->writeNoMutex(12.12 + i); | |
foo->readNoMutex(); | |
#endif | |
})); | |
} | |
for(size_t i = 0, len = all_threads.size(); i < len; i++) { | |
all_threads.at(i)->join(); | |
delete all_threads.at(i); | |
} | |
delete foo; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment