c - remove elements from structure -
i have next code working fine except when element removed, removed parental structure. need parental construction (first_name) remain intact elements:
struct names_list { char username[20]; struct names_list * next; }; pthread_mutex_t name_list; int retu = 0; char username[20]; struct names_list * curr_name = first_name; struct names_list * temp_name = null; while( curr_name != null ) { pthread_mutex_lock(&name_list); strncpy(username, curr_name->username, sizeof( username ) - 1 ); pthread_mutex_unlock(&name_list); //validate retu = validate_name(sock,buff,sizeof(buff),username,domain); switch ( retu ) { case 0: pthread_mutex_lock(&name_list); if (temp_name == null) first_name = curr_name->next; //this used removing when current first record else temp_name->next = curr_name->next; //this used removing current record mid-list free(curr_name);//freeing should needed curr_name = curr_name->next; pthread_mutex_unlock(&name_list); break; case 1: pthread_mutex_lock(&name_list); temp_name = curr_name; curr_name = curr_name->next; pthread_mutex_unlock(&name_list); break; } if (retu == 2) break; } pthread_mutex_lock(&name_list); curr_name = first_name; pthread_mutex_unlock(&name_list);
*how can remove element curr_name , maintain original construction in first_name ?*
here's solution.
struct names_list { char username[20]; struct names_list * next; }; pthread_mutex_t name_list; int retu = 0; char username[20]; struct names_list * temp_list_head=null; struct names_list * prev_list_node=null; struct names_list * curr_name = first_name; struct names_list * temp_name = null; //make re-create of list while (curr_name){ struct names_list *tempnode = malloc(sizeof( struct names_list)); *tempnode = *curr_name; if (temp_list_head== null) temp_list_head = tempnode; if (prev_list_node!=null) prev_list_node->next = tempnode; prev_list_node = tempnode; curr_name = curr_name->next; } curr_name = temp_list_head; while( curr_name != null ) { pthread_mutex_lock(&name_list); strncpy(username, curr_name->username, sizeof( username ) - 1 ); pthread_mutex_unlock(&name_list); //validate retu = validate_name(sock,buff,sizeof(buff),username,domain); switch ( retu ) { case 0: pthread_mutex_lock(&name_list); if (temp_name == null) temp_list_head = curr_name->next; //this used removing when current first record else temp_name->next = curr_name->next; //this used removing current record mid-list free(curr_name);//freeing should needed // curr_name = curr_name->next; //not needed, removed list pthread_mutex_unlock(&name_list); break; case 1: pthread_mutex_lock(&name_list); temp_name = curr_name; curr_name = curr_name->next; pthread_mutex_unlock(&name_list); break; } if (retu == 2) break; } pthread_mutex_lock(&name_list); curr_name = temp_list_head; pthread_mutex_unlock(&name_list);
c struct pthreads
No comments:
Post a Comment