Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <thread>
- #include <mutex>
- #include <memory>
- struct Consumer {
- void consume(const std::shared_ptr<int> aBar)
- {
- const std::lock_guard<std::mutex> myLock(theMutex);
- thePtr = aBar;
- }
- void main_loop() {
- while(1) {
- std::shared_ptr<int> myLocal;
- {
- const std::lock_guard<std::mutex> myLock(theMutex);
- myLocal = thePtr;
- }
- myLocal.use_count();
- }
- }
- std::shared_ptr<int> thePtr;
- std::mutex theMutex;
- };
- struct Producer {
- Producer(Consumer& aConsumer) : theConsumer(aConsumer) {}
- void main_loop() {
- while(1) {
- std::shared_ptr<int> myBar(new int(3));
- theConsumer.consume(myBar);
- myBar.use_count();
- }
- }
- Consumer& theConsumer;
- };
- int main() {
- Consumer myConsumer;
- Producer myProducer(myConsumer);
- std::thread myConsumerThread(&Consumer::main_loop, std::ref(myConsumer));
- std::thread myProducerThread(&Producer::main_loop, std::ref(myProducer));
- myProducerThread.join();
- myConsumerThread.join();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement