Skip site navigation (1)Skip section navigation (2)
Date:      Fri, 3 Jun 2005 19:55:29 -0400
From:      Aziz Kezzou <french.linuxian@gmail.com>
To:        freebsd-hackers <freebsd-hackers@freebsd.org>
Subject:   Fork mystries....
Message-ID:  <3727392705060316555071c4ad@mail.gmail.com>

next in thread | raw e-mail | index | archive | help
Hi all,
It's probably not the right mailing list to ask but I am really
surprised about global variable sharing in a multithreaded C
application. If I remember well my multithreading course global
variables are shared between threads, right ?
=20
Example :
----------------------------
int counter =3D 0;
int main() {
  if( fork()=3D=3D0) {
    while(1) {
      sleep(1);
      counter++;
      printf("Son : counter =3D %d\n", counter);     =20
    }   =20
  } else {
    while(1) {
      sleep(1);
      printf("Parent : counter =3D %d\n", counter);     =20
    }
 }=09=20
  return 0;
}
----------------------------

All I get is :
Parent : counter =3D 0
Son : counter =3D 1
Son : counter =3D 2
Parent : counter =3D 0
Son : counter =3D 3
Parent : counter =3D 0
Son : counter =3D 4
Parent : counter =3D 0

why counter isn't shared between the two threads ??!
thanks,
-aziz



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?3727392705060316555071c4ad>