Question

I have two threads, one thread run an loop to check if there is data received by wait on multiple sockets, and another thread try to add an socket to the socket list or remove one.

The code is as following:

Thread 1:

while (!stop)
{
    // usleep(0)
    AutoLock lock(_socketsLock); // AutoLock will call pthread_lock_mutex/pthread_unlock_mutex.
    Socket* activeSockets = waitOnSockets(_sockets, 50); // Wait 50ms for data on the socket list.
    // Handle the data from socket.
}

Thread 2:

void AddSocket(Socket* socket)
{
     AutoLock lock(_socketsLock);
     _sockets.push_back(socket);
}

The problem is AddSocket seams cannot got the lock in a long time on Android system, I have run the application on Mac, seams the AddSocket wait at most for one loop, but on android it can be 10+seconds.

So I assume the pthread_unlock_mutex doesn't wake up other waiting thread on Android. I can add usleep(0) in the begin of the loop to resolve this issue, even man page of usleep say usleep(0) will be no effect.

But if i add usleep(0) there will always thread switch for each loop, which I think will not be good for mobile device performance.

So what's the alternative way to release CPU when call pthread_unlock_mutex and doesn't case performance issue, in another word only release CPU when there is thread waiting for the lock?

Was it helpful?

Solution

How about:

Thread 1:

while (!stop)
{
    AutoLock addLock(_addLock);
    AutoLock socLock(_socketsLock);

    // Release the addLock here.
    // This gives thread 2 an opportunity to get the first lock while this
    // thread is waiting on the socket.
    AutoRelease addRel(addLock);

    // When this thread finishes it will be forces to sleep if there are
    // any waiting AddSocket requests otherwise it will continue as normal. 
    Socket* activeSockets = waitOnSockets(_sockets, 50);
}

Thread 2:

void AddSocket(Socket* socket)
{
     AutoLock addLock(_addLock);
     AutoLock socLock(_socketsLock);

     _sockets.push_back(socket);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top