Mutex for Simulated Annealing Changing values of global variables

Like many others in this forum I have a critical area in my code and I need to guarantee that not more than one thread run that code at the same time.

int foL = *foM;

int pos1, pos2;


//lock here

if (foL < *foM){

	int temp;

	temp = solutionM[pos1];

	solutionM[pos1] = solutionM[pos2];

	solutionM[pos2] = temp;

	*foM = foL;




solutionM and foM are global.

I read some topics on this forum and I’m really confused about using mutex. Some say it’s not safe, but I think it’s the only option. So how can I make a mutex or some other code for this type of problem (permutation of values of global variables inside a “IF”)?