Sequence of rdlock, rdunlock followed by wrlock,wrunlock in threads causes deadlock

147 views
Skip to first unread message

Ashish

unread,
Nov 29, 2014, 2:35:29 PM11/29/14
to li...@googlegroups.com

This little piece of code should keep running forever without any trouble. However, when I ran it at my end it results in deadlock situation.
I apparently can't see any reason for deadlock. Please can someone have a quick look to ensure I am not doing anything in wrong order here.
(This is on Windows XP. I am using libuv-v1.0.0. Also, I've set threadpool size to 31 before running the code)


#include <uv.h>

uv_work_t gWorkT[31];
uv_rwlock_t g_rwlLock;
void rd_wr_locks_in_thread(uv_work_t* work_t)
{
    static int value = 0;
    while(1)
    {
        uv_rwlock_rdlock(&g_rwlLock);
        BOOL isvalueodd = value % 2;
        uv_rwlock_rdunlock(&g_rwlLock);

        uv_rwlock_wrlock(&g_rwlLock);
        value ++;
        uv_rwlock_wrunlock(&g_rwlLock);
    }
}

void after_rd_wr_locks_in_thread(uv_work_t* work_t, int status)
{
}

int main()
{
    loop = uv_default_loop();

    int retval = uv_rwlock_init(&g_rwlLock);
    if (retval < 0)
    {
        printf("\nError initilizing lock");
        return -1;
    }

    for (int i=0; i<31; i++)
    {
        int RetVal = uv_queue_work(loop, &gWorkT[i], rd_wr_locks_in_thread, after_rd_wr_locks_in_thread);
    }
    return uv_run(loop, UV_RUN_DEFAULT);

}

Ashish

unread,
Dec 1, 2014, 10:59:39 PM12/1/14
to li...@googlegroups.com

Any updates on this please? I investigated it little further and realized libuv relies on only Critical Section objects to synchronize threads.
I suspect there are problems with that approach.

Now if we use read and write locks as demonstrated in the code below, what happens is, a thread enters in a critical section then another thread is very likely to go ahead of it and call leave critical section.

As per Microsoft's documentation,
"If a thread calls LeaveCriticalSection when it does not have ownership of the specified critical section object, an error occurs that may cause another thread using EnterCriticalSection to wait indefinitely."

Bert Belder

unread,
Dec 25, 2014, 1:34:28 PM12/25/14
to li...@googlegroups.com


You're right - the xp/2k3 "fallback" implementation of read-write locks seems broken. A patch would be welcome.
Reply all
Reply to author
Forward
0 new messages