Mutexlock inside or outside function calls?

General FreeBASIC programming questions.
Post Reply
SamL
Posts: 58
Joined: Nov 23, 2019 17:30
Location: Minnesota

Mutexlock inside or outside function calls?

Post by SamL »

Hello every one! thanks to every one posting great info on the forums for freebasic!!

I'm working with threads and i have a question regarding using functions with more then one thread.

here are my explanation examples:
example 1, ( what i would like to do. )

Code: Select all

function myfunc( param_1 )
	MutexLock myfunc_lock
	some_resault += param_1
	MutexUnLock myfunc_lock
	
	return some_resault
end function

sub thread1
	myfunc( 100 )
end sub

sub thread2
	myfunc( 99 )
end sub

example 2, ( what i am doing now to be safe )

Code: Select all

function myfunc( param_1 )
	return some_resault + param_1
end function

sub thread1
	MutexLock myfunc_lock
	myfunc( 100 )
	MutexUnLock myfunc_lock
end sub

sub thread2
	MutexLock myfunc_lock
	myfunc( 99 )
	MutexUnLock myfunc_lock
end sub
I'm worried if i use the example 1 method that the parameters and return might collide and scramble up / change values / go into the breakfast blender .. ( for lack of terminology ).

I have tested example 1 and it seems to not cause errors but im still not convinced its safe as Im not knowledgeable in exactly how functions, parameters and returns work at the lower levels after compiling.

If example 1 is safe then it saves on mutexlocking every function call!

Of course my threads and functions are much more complex then the examples provided but these examples pin point the exact issue at hand.
I have looked up c code and found examples that support example 1 mutexlock use but i would like to be sure.

Regards!
SamL
Last edited by SamL on Nov 24, 2019 8:48, edited 1 time in total.
paul doe
Moderator
Posts: 1745
Joined: Jul 25, 2017 17:22
Location: Argentina

Re: Mutexlock inside or outside function calls?

Post by paul doe »

Generally speaking, you'll want to mutex two threads when they write to the same value. Two threads reading the value at the same time shoulnd't cause issues unless, of course, there's another thread that also needs to write it.

As for the code, both are essentially equivalent but I'd lean towards the first one if my_func is going to be called exclusively from within threads. If my_func is also used by other, non-multithreaded parts of the code, then the second method might prove slightly more efficient (since you're mutexing the calls when you need it and not always). It really depends on your needs; there's not a 'right' or 'wrong' kind of answer to it.
SamL
Posts: 58
Joined: Nov 23, 2019 17:30
Location: Minnesota

Re: Mutexlock inside or outside function calls?

Post by SamL »

Thanks for the help paul. :)
paul doe
Moderator
Posts: 1745
Joined: Jul 25, 2017 17:22
Location: Argentina

Re: Mutexlock inside or outside function calls?

Post by paul doe »

Hey, no prob ;)
Post Reply