-1

I'm now studying multi-thread programming

However, I have a question about while reading Computer Systems: Programmers' Perspective whose author is Bryant

the badcnt.c is written as

#include "csapp.h"

void *thread(void *vargp);
volatile long cnt = 0;
int main(int argc, char **argv){
  long niters;
  pthread_t tid1, tid2;

  niters = atoi(argv[1]);
  Pthread_create(&tid1, NULL, thread, &niters);
  Pthread_create(&tid2, NULL, thread, &niters);
  Pthread_join(tid1, NULL);
  Pthread_join(tid2, NULL);

  printf("cnt = %ld\n", cnt);
}

void *thread(void *vargp){
  long i;
  long niters = *((long *) vargp);
  for(i = 0; i < niters; i++) cnt++;

  return NULL;
}

I know that in uniprocessor, the machine instructions are completed one after the other in some order, so the cnt result can be from 10 to 20.

My question is

Does cnt result's range can be different from 10 to 20 in dual-core?

In simple thought, I don't think so, but I want to hear many people's opinion.

Thanks

1 Answers1

2

You have some race condition which is an undefined behavior. So anything could happen (according to the specs), including the collapse of the entire universe (or nasal daemons). Be scared.

You need to dive into implementation details to understand what is really happening, and you don't want to... (and you probably cannot grasp all the details).

In practice, you probably use some operating system like Linux (or perhaps another POSIX one, like MacOSX). There are more than two runnable tasks (check with top, htop, ps; imagine some thrashing situation), and the kernel scheduler can choose any of them for each core (on my Linux desktop there is more than 200 processes, most of them usually -but not always- idle). So you cannot predict reliably what happens. To learn more, read Operating Systems: Three Easy Pieces.

Read some pthread tutorial. BTW, notice that Pthread function names all start with pthread_ in lowercase.

Concretely speaking, your intuition (cnt between 10 and 20) is probably good. But you have no guarantee. Details depend on too many things: your processor instruction set architecture and model (so could be different on AMD and on Intel), its cache, your compiler and optimization flags, the generated machine code, your operating system, the other processes running on your machine, the interrupts (e.g. from timers, external network packets, mouse movement, ...) etc.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547