segmnetation fault by pthread_mutex_unlock on a successfully locked mutex

Hi Everyone

I have this quite simple "tread" function

void* row_calc(void *input)
{
	struct thread_arg* th_arg;
	th_arg=(struct thread_arg *) input;
	int start,width,end,seg,k,l,tmp;
	
	start=th_arg->start;
	width=th_arg->width;
	end=start+width-1;
	seg=th_arg->seg;
	
	fprintf(logger,"Segment %d: Hello Start: %d\t End: %d\n\n",seg,start,end);
	fflush(logger);
	
	
	if(th_arg->up_neighbour != NULL)
	{
		fprintf(logger,"Segment %d: Before Up_Neighbour Mutex Lock\n",seg);
		fflush(logger);

		pthread_mutex_lock(th_arg->up_neighbour);
                perror("");

		fprintf(logger,"Segment %d: After Up_Neighbour Mutex Lock\n\n",seg);
		fflush(logger);
		
		for (k=1;k<NC-1;k++)
			after[start][k]=0.25*(before[start-1][k]+before[start+1][k]+before[start][k-1]+before[start][k+1]);

		fprintf(logger,"Segment %d: Before Up_Neighbour Mutex UnLock\n",seg);
		fflush(logger);
		
		pthread_mutex_unlock(th_arg->up_neighbour);

		fprintf(logger,"Segment %d: After Up_Neighbour Mutex UnLock\n\n",seg);
		fflush(logger);
	}
	fprintf(logger,"Segment %d: Ok, Bye Bye!\n",seg);
	fflush(logger);
}

I can't unlock the mutex pointed by th_arg->up_neighbour, I'm getting a segmentation fault.The mutex is previously successfully locked, perror prints success.

The aren't any race conditions,since only one thread is created in main()

int main()
{
	int tmp,i,j;
	int width=NR/NT;
	pthread_mutex_t border[NT-1];
	pthread_t row_worker[NT];

	logger=fopen("treads.log","w");
	for(i=0;i<NR;i++)
	{
		for (j=0;j<NC;j++)
		{
			before[j]=0.0;
			after[j]=0.0;
		}
	}

	for(i=0;i<2*NT-2;i++)
	{
		pthread_mutex_init(border+1,NULL);
	}

	tmp=0;
	for(i=0;i<NT;i++)
	{
		printf("TEST\n");
		arg_vec.up_neighbour=(i==0)?NULL:(border+(tmp++));
		arg_vec.up=(i==0)?NULL:(border+(tmp++));
		arg_vec.down=(i==NT-1)?NULL:(border+(tmp));
		arg_vec.down_neighbour=(i==NT-1)?NULL:(border+(tmp+1));

		arg_vec.start=i*width;
		arg_vec.width=(i==NT-1)?width:width+NR%NT;
		arg_vec.seg=i+1;
}

pthread_create(row_worker+NT-1,NULL,row_calc,(void *)(&arg_vec[NT-1]));

pthread_join(row_worker[NT-1],NULL);
printf("That's all folks\n");

The struct of arguments passed is declared as global

double before[NR][NC], after[NR][NC];

struct thread_arg
{
	pthread_mutex_t *up, *up_neighbour;
	pthread_mutex_t *down, *down_neighbour;
	int start;
	int width;
	int seg;
};

struct thread_arg arg_vec[NT];
FILE *logger;

My log file finishes with line "Segment %d: Before Up_Neighbour Mutex UnLock\n" so I know it's not the critical code section.I even tried commenting out.

Any advice ? Thank you in advance

I found my errors...

mutex array size didn't match the initialization loop.
&
inside initialization loop mispelled i with 1.

Excuse me for this useless thread...:frowning:

This is not at all useless.

Indeed very helpful and useful for me.

Thanks for this post. :slight_smile: