相关代码可在以下位置找到: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;
}

最佳答案

您有一种有趣且错误的初始化互斥量的方式:

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);

09-11 17:48