Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some questions about global variables in multi-threaded programming

Here is my code:

#include <stdio.h>
#include <unistd.h>

static volatile int t=0;

int main(void){
    int i;
    for (i=0; i<2; i++){
        fork();
        printf("pid:%d: addr:%d val:%d\n", getpid(), &t, t++);
    }
    printf("pid:%d: addr:%d val:%d\n", getpid(), &t, t++);
    return 0;
}

the output like that:

pid:16232: addr:134518684 val:0
pid:16233: addr:134518684 val:0
pid:16232: addr:134518684 val:1
pid:16232: addr:134518684 val:2
pid:16234: addr:134518684 val:1
pid:16234: addr:134518684 val:2
pid:16233: addr:134518684 val:1
pid:16233: addr:134518684 val:2
pid:16235: addr:134518684 val:1
pid:16235: addr:134518684 val:2

The address of global variable t is same, does all threads operate the same variable t? I expect the val was "0, 1, 2, 3, 4, 5, ...", how should I do?

like image 696
solomon_wzs Avatar asked Dec 05 '25 08:12

solomon_wzs


1 Answers

This is forking a different process, NOT spawning new threads. The result makes sense, since the forked processes will get a copy of the parent process memory.

If its your intention to use forks, this is a more standard way to do it:

int main ()
{
   int pid;

   pid = fork();

   if (pid == 0) {
      // This will be where the child process executes
   } else if (pid > 0) {
     // This is where the parent process executes
   }
   return 0;
}
like image 158
Brady Avatar answered Dec 07 '25 21:12

Brady



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!