dimanche 3 juillet 2016

Reader - Writer exercise C++11 without semaphores doesn't release resource

I tried to implement the reader-writer problem to practise concurrency, but I can't understand what it is not working fine. I implemented a simple solution (not solve starvation for writers) with C++ mutexs, but It seems writer or reader get the resource and they don't release it, I don't know why. It only prints the output for the reader or for the writing. It doesn't change, and it prints one time the count..

Note : I suppose It would work better with std::atomic count_readers(0); instead of an int count_readers=0; but this variable is protected via mutex, it should not give problems..

This my code:

#include <iostream>
#include <atomic>
#include <thread>
#include <chrono>
#include <mutex>

std::atomic_bool finish_reader(false);
std::atomic_bool finish_writer(false);


void reader() {
    while (!finish_reader) {
        std::cout  <<"I am reading" << '\n';
    }
    std::cout << "It is finished reader" << '\n';
}
void writer() {
    while(!finish_writer) {    
        std::cout << "I am writing" << '\n';
    }
    std::cout << "It is finished writer" << '\n';
}


std::mutex mutex_reader;
std::mutex mutex_writer;
int count_readers=0;
void multiple_lock_reader() {

    mutex_reader.lock();
    count_readers++;
    if (count_readers==1) {
        mutex_writer.lock();    
    }
    std::cout << "count_readers: "<< count_readers<<'\n';
    mutex_reader.unlock();  
    reader();

    mutex_reader.lock();
    count_readers--;
    if (count_readers==0) {
        mutex_writer.unlock();  
    }
    mutex_reader.unlock();  
}
void multiple_lock_writer() {
    mutex_writer.lock();
    writer();
    mutex_writer.unlock();

}

void versionMultipleLockSync() {
    std::thread tReader(multiple_lock_reader);
    std::thread tWriter(multiple_lock_writer);
    std::this_thread::sleep_for(std::chrono::seconds(4));

    finish_reader = true;
    finish_writer = true;
    tReader.join();
    tWriter.join();
}


int main () {
    versionMultipleLockSync();
}

Aucun commentaire:

Enregistrer un commentaire