[LCP] Multi threading programming
ishwor
ishwor at tpg.com.au
Fri Feb 20 19:42:26 EST 2009
Hi there,
I think what Robert pointed out was exactly what i was going to say
with basic premise being (I am no thread guru though) -
Lock
....operation on exclusive code....
Unlock
resume....
also have a read at the PTHREAD_MUTEX(3).
here's the basic theory stuff from it-
" A mutex has two possible states: unlocked (not owned by any thread),
and locked (owned by one thread). A mutex can never be owned by two
different threads simultaneously. A thread attempting to lock a
mutex that is already locked by another thread is suspended until the
owning thread unlocks the mutex first."
Be careful of "suspended" bit above making sure that mutex is not
locked by some other thread before you proceed in your critical section
so try a trylock - pthread_mutex_trylock(pthread_mutex_t *mutex) see if
you can actually gain a lock/not or else return immediately.
Regards,
Ishwor
Robert Wuest wrote:
> wrap accesses to the global thing in a mutex:
>
> #include <pthread.h>
> static pthread_mutex_t counter_mutex = PTHREAD_MUTEX_INITIALIZER;
> int my_global_counter;
>
>
> then, to access my_gloab_int, use sequences like:
>
> pthread_mutex_lock(&counter_mutex);
> my_global_counter++;
> pthread_mutex_unlock(&counter_mutex);
>
> Don't sleep with the mutex locked.
>
> Compile with -pthread as one of your flags.
>
> Robert
>
> On Thu, 2009-02-19 at 13:21 -0900, Christopher Howard wrote:
>> I'm am entirely unexperienced at multi threaded programming, but am about
>> to try and figure it out. For one of my programs I wanted to create a
>> simple "internal counter" function which which sleeps for 1000
>> milliseconds, then increments a global variable which other functions can
>> read. (I know this doesn't work as an accurate clock, but that is okay.)
>>
>> My question: Does the global variable have to be some kind of atomic
>> variable? Will this still work correctly if it is an int or a long int? I
>> read something on the Internet about locking variables... does that apply
>> here?
>>
>> Any (simple) examples would also be appreciated. Thank you in advance.
>>
>
>
> _______________________________________________
> This is the Linux C Programming List
> : http://lists.linux.org.au/listinfo/linuxcprogramming List
>
>
>
More information about the linuxCprogramming
mailing list