[LCP] Multi threading programming
Robert Wuest
rwuest at wuest.org
Fri Feb 20 11:28:19 EST 2009
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.
>
More information about the linuxCprogramming
mailing list