Pthread Mutex挂在一个线程中

时间:2014-04-17 20:31:30

标签: c pthreads mutex

在我用C编写的进程中,我有三个线程如下: 1.第一个线程处理侦听和接受新的TCP连接。 2.为每个新的新连接调度第二个线程,并读取视频文件并将其流回客户端。 3.第三个线程侦听来自其他应用程序(即IPC)的UDP套接字上发生的事件。

这是我读取所请求的视频文件并将其写入套接字的代码,我尝试锁定和解锁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;

在第三个线程中,当一个事件到来时,我尝试搜索其相应的用户,并获取互斥量来做一些事情,但线程在尝试获取互斥量时遇到问题并且不执行打印在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");
    }
}
}

可能出现什么问题?

2 个答案:

答案 0 :(得分:0)

如果/当线程2突破循环时,它不会解锁互斥锁。

答案 1 :(得分:0)

我发现了问题,这是我的错误。当我得到一个新的请求时,我为用户创建了一个新的结构,然后我将它添加到unordered_map,稍后我继续将结构作为对象处理,但是我必须得到已添加到无序地图的结构布设。

正如我认为无序映射不会将结构视为自身并将其添加到其容器中,而是创建自己的克隆。

相关问题