I am trying to initiate a recursive mutex but unable to succeed. This is my code:
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));
}
On printf i always get
dead or alive lock is of type 0.
i.e the mutex stays PTHREAD_MUTEX_DEFAULT after the call to pthread_mutexattr_settype()
The wrapping functions called from main().
This is the code before the call:
// 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();
Any suggestions?
The value of the attribute object is used at the time you initialize the mutex. Changing it after you create the mutex is not useful. Switch the order of operations so that you set the attribute first before using it to initialize the mutex.