我已經使用C++ 14的shared_timed_mutex編寫了讀寫器問題的實現。在我看來,下面的代碼應該會導致Writer餓死,因爲太多的讀取線程一直在數據庫上工作(在這個例子中是一個簡單的數組):作者沒有機會獲得鎖。如何讓作者線程餓死
mutex cout_mtx; // controls access to standard output
shared_timed_mutex db_mtx; // controls access to data_base
int data_base[] = { 0, 0, 0, 0, 0, 0 };
const static int NR_THREADS_READ = 10;
const static int NR_THREADS_WRITE = 1;
const static int SLEEP_MIN = 10;
const static int SLEEP_MAX = 20;
void read_database(int thread_nr) {
shared_lock<shared_timed_mutex> lck(db_mtx, defer_lock); // create a lock based on db_mtx but don't try to acquire the mutex yet
while (true) {
// generate new random numbers
std::random_device r;
std::default_random_engine e(r());
std::uniform_int_distribution<int> uniform_dist(SLEEP_MIN, SLEEP_MAX);
std::uniform_int_distribution<int> uniform_dist2(0, 5);
int sleep_duration = uniform_dist(e); // time to sleep between read requests
int read_duration = uniform_dist(e); // duration of reading from data_base
int cell_number = uniform_dist2(e); // what data cell will be read from
int cell_value = 0;
// wait some time before requesting another access to the database
this_thread::sleep_for(std::chrono::milliseconds(sleep_duration));
if (!lck.try_lock()) {
lck.lock(); // try to get the lock in blocked state
}
// read data
cell_value = data_base[cell_number];
lck.unlock();
}
}
void write_database(int thread_nr) {
unique_lock<shared_timed_mutex> lck(db_mtx, defer_lock); // create a lock based on db_mtx but don't try to acquire the mutex yet
while (true) {
// generate new random numbers
std::random_device r;
std::default_random_engine e(r());
std::uniform_int_distribution<int> uniform_dist(SLEEP_MIN, SLEEP_MAX);
std::uniform_int_distribution<int> uniform_dist2(0, 5);
int sleep_duration = uniform_dist(e); // time to sleep between write requests
int read_duration = uniform_dist(e); // duration of writing to data_base
int cell_number = uniform_dist2(e); // what data cell will be written to
// wait some time before requesting another access to the database
this_thread::sleep_for(std::chrono::milliseconds(sleep_duration));
// try to get exclusive access
cout_mtx.lock();
cout << "Writer <" << thread_nr << "> requesting write access." << endl;
cout_mtx.unlock();
if (!lck.try_lock()) {
lck.lock(); // try to get the lock in blocked state
}
// write data
data_base[cell_number] += 1;
lck.unlock();
}
}
我添加了一些輸出到當一個線程正在讀取標準輸出,寫入,試圖獲取鎖無論在阻塞模式或通過try_lock()
方法,但我刪除爲清楚起見的輸出。我在主要方法中進一步開始線程。當我運行程序時,作者總是有機會寫入數組(導致所有讀者線程被阻塞,這是可以的),但正如我上面所說,作者應該無法訪問,因爲也有許多閱讀器線程從數組中讀取。即使我不讓讀者線程進入睡眠狀態(參數0),作者線程也會找到一種方法來獲得互斥鎖。那我該如何讓作家餓死?
你正在使用哪個std :: lib? –
@HowardHinnant只是C++十四分之十一內部同步機制: –
kimsay
噢,我想知道gcc的的libstdC++,VS,libc的+ +?不重要,只是好奇。 –