The following piece of pseudo-code shows a typical reader / writer scenario:
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();
}
My question is:
Where can concurrent execution problems occur in this program?
And how they should be protected only using the pseudo-code functions lock ()
and unlock ()
?
There is not much known about your code but I'm assuming, that neither
document
norlength
are atomic. What you would need here is a distinction between write access and read access (assuming that read access is const). Writing will change document and length and must be protected from other accesses. Reading must be protected from changes by the write call, but since reading does not alter neither document nor length it is allowed to be done in multiple threads at once.I'm taking the liberty to use
lock_write()
andlock_read()
. Doing this with full lock() calls, would make mostread
-threads useless. Also, I'm taking the liberty to fix thispos = length - 1
-thing you have in yourread()
function.write()
will become:And
read()
will become:Also,
read()
will go into a busy wait, which is not nice. This could be fixed, using a condition variable.