无法启动递归互斥体

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

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

有什么建议吗?

suzhuang 回答:无法启动递归互斥体

在初始化互斥锁时使用属性对象的值。创建互斥锁后对其进行更改无济于事。切换操作顺序,以便在使用属性初始化互斥之前先设置属性。

,
printf("dead or alive lock is of type %d\n",pthread_mutexattr_gettype(&dead_or_alive_attr,&type));

即互斥体保持PTHREAD_MUTEX_DEFAULT

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

本文链接:https://www.f2er.com/2801302.html

大家都在问