pthread_mutex_lock卡住了

时间:2014-04-15 08:51:32

标签: c multithreading mutex

可以在此处找到引人注目的代码:http://pastebin.com/VbhtQckm
问题是在线 85. pthread_mutex_lock(ID_retrieval_pool->info->lock);

我正在运行服务器并且它已经陷入困境。内存已分配,我正在初始化互斥锁,它是拥有该共享内存的唯一线程。
我使用helgrind工具对GDB和Valgrind进行了调试,但没有发现任何线索。 可能出现的问题可能导致这种情况:

  • 互斥锁未初始化(我使用块是共享内存,我初始化为互斥锁);
  • 死锁?在手册页https://www.sourceware.org/pthreads-中 win32 / manual / pthread_mutex_init.html说这会导致这个;

请注意,此代码仅供学习使用。

编辑,代码为:

// common_header.h + common_header.c
#ifndef DATA_TYPES_H
#define DATA_TYPES_H

#include <pthread.h>
#include <errno.h>

#define RETREIVE_ID_KEY 1

typedef enum {
  SHM_State_None,
  SHM_State_ID_Available,
  SHM_State_ID_Not_Available,
} SHM_State;

typedef struct {
    pthread_mutex_t *lock; // locked if any thread is modifying data
    SHM_State state;
} data_state;

typedef int shmid_t;

typedef struct data_pool {
    data_state *info;
    shmid_t shm_id;
} data_pool;

// other data structures

extern data_state * data_state_initialize_by_setting_address(void *address)
{
  data_state *data = (data_state *)address;
  data->lock = (pthread_mutex_t *)address;
  pthread_mutex_init(data->lock, NULL);
  data->state = SHM_State_None;

  return data;
}
extern data_pool * data_pool_initialize_by_setting_address(void *address)
{
  data_pool *data = (data_pool *)address;
  data->info = data_state_initialize_by_setting_address(address);
  data->shm_id = 0; // invalid though, the structure's client has to set a valid one

  return data;
}
// other initialization functions

#endif // DATA_TYPES_H

///----------------------------------------------------------------------------------------\\\

// main.c -- Server
#include "common_header.h"

#define SHM_INVALID_ADDRESS (void *)-1
#define SHMGET_RW_FLAGS 0666
#define SHMAT_RW_FLAGS 0

bool initialize_data();

static data_pool *ID_retrieval_pool = NULL;

int main(int argc, char *argv[])
{
  if (!initialize_data()) {
    return EXIT_FAILURE;
  }
  // Do other stuff

  return EXIT_SUCCESS;
}

bool initialize_data()
{
  // some irrelevant initialization code
  shmid_t shm_ID = shmget(RETREIVE_ID_KEY,
                          sizeof(data_pool),
                          IPC_CREAT | SHMGET_RW_FLAGS);
  void *shm_address = shmat(shm_ID, NULL, SHMAT_RW_FLAGS);
  if (shm_address == SHM_INVALID_ADDRESS) {
    return false;
  }
  ID_retrieval_pool = data_pool_initialize_by_setting_address(shm_address);
  pthread_mutex_lock(ID_retrieval_pool->info->lock);
  ID_retrieval_pool->shm_id = get_shared_ID();
  ID_retrieval_pool->info->state = SHM_State_ID_Available;
  pthread_mutex_unlock(ID_retrieval_pool->info->lock);

  // other initialization code

  return true;
}

1 个答案:

答案 0 :(得分:1)

您有一种有趣且不正确的初始化互斥锁的方法:

data->lock = (pthread_mutex_t *)address; /* address == &data */
pthread_mutex_init(data->lock, NULL);

在您的代码中address是外部结构的地址:这实际上并不分配可用的内存块。

我建议你只需要使用互斥锁非指针,然后将其初始化:

/* In the struct. */
pthread_mutex_t lock;

/* In your function. */
pthread_mutex_init(&data->lock, NULL);