1
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include "pthread.h"
#include "semaphore.h"

FILE * f;
sem_t * s1;
sem_t * s2;
int check;
int  v1;
int  v2;
int i;

static void * client (void *arg){


    sem_getvalue(s1, &v1); printf("Client pre wait(S1) in S1 => S1 = %d\n",v1);
    sem_wait(s1);
    printf("client works...\n");
    check = sem_getvalue(s1, &v1); printf("Client.wait(S1) in S1 => S1 = %d\n",v1);
    if(check != 0) printf("sem_getvalue error");


     return 0;
    }


int main(void){

    pthread_t tidc;
    pthread_t tids;
    int rc;
    int rs;

    //Semaforo 1
    s1 = (sem_t *) malloc(sizeof(sem_t));
    check = sem_init (s1, 0, 2);
    if (check != 0) perror("s1_init failed");




    sem_getvalue(s1, &v1);

    printf("Create the semaphores: S1 = %i\n",v1 );

    sem_wait(s1);
    printf("main waits\n");
    sem_getvalue(s1, &v1); printf("Main.wait(S1) in S1 => S1 = %d\n",v1);

    rc = pthread_create (&tidc, NULL, client, 0);
    printf(" thread created ==> rc= %i\n",rc);


    return 0;

   }

It returns this output:

Create the semaphores: S1 = 2
main waits
Main.wait(S1) in S1 => S1 = 1
 thread created ==> rc= 0

And sometimes this:

 Create the semaphores: S1 = 2
main waits
Main.wait(S1) in S1 => S1 = 1
 thread created ==> rc= 0
Client pre wait(S1) in S1 => S1 = 1
Client pre wait(S1) in S1 => S1 = 1
client works...
Client.wait(S1) in S1 => S1 = Client.wait(S1) in S1 => S1 = 0

Seems like sometimes creates two threads and sometimes no one. I compile with gcc prog.c -lpthred and even with gcc -pthread prog.c

  • Possible duplicate of [main thread exit, does other exit too?](http://stackoverflow.com/questions/11875956/main-thread-exit-does-other-exit-too) – tofro Mar 18 '17 at 10:20

1 Answers1

0

If a multithreaded program doesn't do the same thing from one execution to another, it could be because of uninitialized variables (like in non-threaded programs), but also can be because of a race condition.

In that case, the race condition is between thread execution and program exit.

Since you're exiting your main immediately after creating your threads, threads are terminated (main thread exit, does other exit too?). Sometimes, the thread has the time to do something, depending on the OS state & load.

If you add some actual processing, a long delay or a call to pthread_join(tdic,NULL); to wait for thread termination in your main program, you'll have deterministic behaviour.

Community
  • 1
  • 1
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219