Question

In my process which is written in C, I have three threads as following: 1. The first thread handles listening and accepting new TCP connections. 2. The second thread is dispatched for each new new connection, and read a video file and stream it back to the client. 3. The third thread listen for an events coming on UDP sockets from other application i.e. IPC.

Here is the code for which I read the requested Video file and write it to the socket, I try to lock and unlock a Mutex as following to give the third thread later an ability to acquire the Mutex:

        /* Read till end of file is not reached. */
        while (1) /* Loop forever */
        {
            len = fread(read_buf, 1, 1024, pf);
            pthread_mutex_lock(&client->mutex);

            /* Write to the socket. */
            if (write(client->fd, read_buf, len) <= 0)
                break;

            if (len < 1024)
            {
                /* Reset to the begining of the file. */
                fseek(pf, 0L, SEEK_SET);
                break;
            }

            client->offset = ftell(pf);
            pthread_mutex_unlock(&client->mutex);
            usleep(5);
        }
        fclose(pf);
        client->state = 4;

In the third thread, when an event arrives I try to search for its corresponding user, and acquire the mutex to do some stuff, but the problem the thread gets stuck when trying to acquire the mutex as following and does not do the printing below the pthread_mutex_lock

int handle_event(EVENT_TYPE event, TransactionID t_id, void *data)
{
switch (event)
{
    case PREPARE_TO_EXPORT:
    {
            // Searching for the client if the client is found do the below
            printf("Prepared to export.\n");
            pthread_mutex_lock(&client->mutex);
            printf("Handling Export\n");
    }
}
}

What could be the possible problem?

Was it helpful?

Solution 2

I found the problem, it was my mistake. When I get a new request I create a new struct for the user and I add it to an unordered_map, later on I continue dealing with the struct as object, but instead I have to get the struct which has been added to the unordered map using emplace.

As what I think the unordered map does not take the struct as it self and add it to its container, instead it creates its own clone of it.

OTHER TIPS

If/when thread 2 breaks out of the loop, it doesn't unlock the mutex.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top