0

我正在尝试启动递归互斥锁但无法成功。这是我的代码:

void init_locks_and_conds() {
    int type; // TODO DELETE
    if (pthread_mutexattr_init(&dead_or_alive_attr)) {perror(""); exit(1);}
    else if (pthread_mutex_init(&queue_lock, NULL)) {perror(""); exit(1);}
    else if (pthread_mutex_init(&errno_lock, NULL)) {perror(""); exit(1);}
    else if (pthread_mutex_init(&dead_or_alive_lock, &dead_or_alive_attr)) {perror(""); exit(1);}
    else if (pthread_cond_init(&queue_cond, NULL)) {perror(""); exit(1);}
    else if (pthread_mutexattr_settype(&dead_or_alive_attr, PTHREAD_MUTEX_RECURSIVE)) {perror(""); exit(1);}
    else{}
    printf("dead or alive lock is of type %d\n", pthread_mutexattr_gettype(&dead_or_alive_attr, &type));
}

在 printf 我总是得到

死锁或活锁的类型为 0。

即互斥锁在调用 pthread_mutexattr_settype() 后保持 PTHREAD_MUTEX_DEFAULT

从 main() 调用的包装函数。

这是调用前的代码:

// global variables
struct Queue *dir_queue; // queue of directories
int num_of_threads = 0;
int files_found = 0; // counts how many matching files we found
int working_threads; // number of threads working
int error_threads = 0; // number of threads went to error
const char* search_term; // sub string to search in files names
pthread_t* thread_arr; // array of thread id's. To be allocated according to argv[3]
int* dead_or_alive; // dead_or_alive[i] holds for thread # thread_arr[i] is dead or alive
pthread_mutex_t queue_lock;
pthread_mutex_t errno_lock;
pthread_mutex_t dead_or_alive_lock;
pthread_mutexattr_t dead_or_alive_attr;
pthread_cond_t queue_cond;
int cancel = 0; // when SIGINT is sent update "cancel = 1"  
int initiallized = 0; // indicator if we initiallized thread_arr

//---------------------------------Flow--------------------------------------
int main(int argc, char** argv) {
    char *root_dir_name;
    int i;
    void* status;

    // register SIGINT handler
    struct sigaction SIGINT_handler;
    register_handler(&SIGINT_handler, my_SIGINT_handler, SIGINT);

    if (argc != 4) {
        fprintf(stderr, "Wrong number of arguments\n"); 
        exit(1);
    }

    root_dir_name = (char*) malloc(strlen(argv[1]));
    if (root_dir_name == NULL) {
        fprintf(stderr, "Failed to allocate memory\n");
        exit(1);
    }
    strcpy(root_dir_name, argv[1]);

    search_term = argv[2];
    num_of_threads = atoi(argv[3]);
    working_threads = num_of_threads;

    if (!opendir(root_dir_name)) {
        perror(""); 
        exit(1);
    }

    // initiallization
    init_locks_and_conds();

有什么建议么?

4

2 回答 2

2

属性对象的值在您初始化互斥锁时使用。创建互斥锁后更改它没有用。切换操作顺序,以便在使用它初始化互斥体之前先设置属性。

于 2020-01-08T22:15:18.870 回答
0
printf("dead or alive lock is of type %d\n",
       pthread_mutexattr_gettype(&dead_or_alive_attr, &type));

即互斥体保持 PTHREAD_MUTEX_DEFAULT

您显示的代码实际上并未表明这一点。0 返回值pthread_mutexattr_gettype仅表示成功完成,而不是实际的互斥锁类型。要检查类型,您需要显示type您已将其地址传递给函数的变量的值。

于 2020-01-08T22:18:17.990 回答