UC3M

Telematic/Audiovisual Syst./Communication Syst. Engineering

Systems Architecture

September 2017 - January 2018

11.2.2.  Turnning to not concurrent execution

You can see the difference with a sequential code execution, carrying out some changes in the previous examples. In our example, if we replace the call to the pthread_create with a thread_run function call, as a result the code stops running concurrently. The following piece of code shows that threre is not concurrent execution. For it has been altered as little as possible, the original code; the resulting code is this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// compile with $ gcc -Wall -g *.c -pthread -o program
// run with ./program
// check with valgrind --tool=helgrind ./program
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>

void* thread_run(void* data)
{ //sleep(2); 
  printf("[TH_1 %ld]: Hello from the thread \n",pthread_self());
  sleep(1);
  (*(int*)data)++;
  printf("[TH_1 %ld]: To exit...............\n",pthread_self());
  //pthread_exit(data);
  return data;
}

int main()
{
  pthread_t thread;
  int data=0;
  int thread_rc=0;
  printf("[MAIN %ld]: Starting............ \n",pthread_self());
  thread_run(&data);
  /*if ((thread_rc=pthread_create(&thread,NULL,thread_run,&data))!=0)
  {
    printf("Error creating the thread. Code %i",thread_rc);
    return -1;
  }*/
  sleep(1);
  printf("[MAIN %ld]: Thread allocated \n",pthread_self());
  int *ptr_output_data;
  //pthread_join(thread,(void **)&ptr_output_data);
  printf("[MAIN %ld]: Thread returns %d \n",pthread_self(),data);
  return 0;
} 

With that change in the execution, regardless of the uses of sleep does, the resulting sequence of messages would be:

 ./pthreads_create_join_main_nothreads 
[MAIN:0]: Starting............ 
[MAIN:0]: Thread allocated 
[TH_1:0]: Hello from the thread 
[TH_1:0]: To exit...............
[MAIN:0]: Thread returns 1  

This is so because with threads, the advantage of concurrent execution disappears. In the concurrent version there are as many variations as combinations between the instructions executed by the two threads, because that is the programming pattern provided by the execution platform.