I am implementing a thread safe function to create directory if it does not exist.
void create_directory(char *str){
pthread_mutex_lock(mutex);
if (stat(str, &st) == -1) {
mkdir(str, 0700);
}
pthread_mutex_unlock(mutex);
}
Thread_1:
create_directory("dir1");
Thread_2:
create_directory("dir1");
Thread_3:
create_directory("dir2");
Thread_1 and Thread_2 are trying to create same directory, and and code works as expected. Problem is when Thread_3 tries to create another directory, i.e. "dir2", which has got nothing to do with directory "dir1", then Thread_3 is also get blocked.
What I want is to have lock on a directory instead of lock on a code section. How can I achieve this.
Or is there any other way to implement thread safe function to create directory. Or is there any function in C to do this.