LaPlace
LaPlace

Reputation: 1

Where could be any problems in the program and how i solve them with using lock() and unlock()?

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 ()?

Upvotes: 0

Views: 54

Answers (1)

Xoozee
Xoozee

Reputation: 488

There is not much known about your code but I'm assuming, that neither document nor length 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() and lock_read(). Doing this with full lock() calls, would make most read-threads useless. Also, I'm taking the liberty to fix this pos = length - 1-thing you have in your read() function.

write() will become:

write()
{
    while (true) {
        string text = readFromKeyboard();
        lock_write();
        document.append(text);
        length = length + text.length();
        unlock();
    }
}

And read() will become:

read()
{
    static string::size_type pos = 0;
    while (true) {
        lock_read();
        if (pos < length) {
            process(document.substr(pos, length - pos));
            pos = length;
        }
        unlock();
    }
}

Also, read() will go into a busy wait, which is not nice. This could be fixed, using a condition variable.

Upvotes: 1

Related Questions