Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.programming.threads > #845

Mutex required for a simple shared-variable case?

From Lasse Kliemann <lasse-usenet-2011@mail.plastictree.net>
Newsgroups comp.programming.threads
Subject Mutex required for a simple shared-variable case?
Date 2012-04-03 15:31 +0200
Organization Altopia Corp. - Usenet Access - www.altopia.com
Message-ID <5hbjd7.krj.17.1@news.alt.net> (permalink)

Show all headers | View raw


A number of threads execute a loop each. Once one of them finds a 
certain condition, it shall signal all the other threads to stop.

My first idea was to implement this with a shared variable. It is 
passed to each of the threads as a pointer to an integer, say 
'go_on'. It is set to 1 in the beginning, before the threads 
start. If any of the threads finds the stopping condition given, 
it sets this variable to 0 and terminates. Each of the loops 
looks like this:

for(...; ... && (*go_on); ...) { ...

So it will not do another iteration if the place pointed to by 
'go_on' shows 0.

Inside the loop, the stopping condition is checked for:

   if ...; *go_on = 0;

Are there any mutexes required to read or write to the place 
pointed to by 'go_on'?

All resources on thread programming emphasize how important 
mutexes are for shared data. But I do not quite see why it should 
be necessary in such a simple case. And for performance reasons, 
I would rather keep it as simple as possible.

Can someone give me a quick explanation? I would be satisfied 
with a Pthreads-specific answer, since that's what I am using.

Thank you!

Back to comp.programming.threads | Previous | Next — Next in thread | Find similar | Unroll thread


Thread

Mutex required for a simple shared-variable case? Lasse Kliemann <lasse-usenet-2011@mail.plastictree.net> - 2012-04-03 15:31 +0200
  Re: Mutex required for a simple shared-variable case? Marcel Müller <news.5.maazl@spamgourmet.com> - 2012-04-04 01:45 +0200
  Re: Mutex required for a simple shared-variable case? Joshua Maurice <joshuamaurice@gmail.com> - 2012-04-05 17:08 -0700

csiph-web