[英]Where could be any problems in the program and how i solve them with using lock() and unlock()?
下面的一段偽代碼展示了一個典型的讀寫器場景:
string document;
string::size_type length = 0;
write()
{
while (true) {
string text = readFromKeyboard();
document.append(text);
length = length + text.length();
}
}
read()
{
static string::size_type pos = 0;
while (true) {
if (pos < length) {
process(document.substr(pos, length - pos));
pos = length - 1;
}
}
}
main()
{
unsigned int k = 20;
while (k--)
Thread consumer(read).start;
Thread producer(write).start;
wait();
}
我的問題是:這個程序中哪里會出現並發執行問題? 以及如何僅使用偽代碼函數lock ()
和unlock ()
來保護它們?
關於您的代碼知之甚少,但我假設document
和length
都不是原子的。 您需要在這里區分寫訪問和讀訪問(假設讀訪問是 const)。 書寫會改變文檔和長度,並且必須防止其他訪問。 必須通過 write 調用來保護讀取免受更改,但由於讀取既不會改變文檔也不會改變長度,因此允許同時在多個線程中完成。
我冒昧地使用lock_write()
和lock_read()
。 使用完整的 lock() 調用來執行此操作會使大多數read
線程無用。 另外,我冒昧地修復這個pos = length - 1
你在read()
function 中的東西。
write()
將變為:
write()
{
while (true) {
string text = readFromKeyboard();
lock_write();
document.append(text);
length = length + text.length();
unlock();
}
}
並且read()
將變為:
read()
{
static string::size_type pos = 0;
while (true) {
lock_read();
if (pos < length) {
process(document.substr(pos, length - pos));
pos = length;
}
unlock();
}
}
此外, read()
將使 go 進入忙碌等待狀態,這並不好。 這可以使用條件變量來修復。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.