vendredi 1 juillet 2016

c - running 2 threads in parallel with a shared variable

Just a beginner to threads, I'm just doing a task which involves these 2 threads.

#include <stdio.h>
#include <pthread.h>

int count = 0;

void waitFor(unsigned int secs)
{
    unsigned int retTime = time(0) + secs;
    while(time(0) < retTime);
}

void func1(void * args)
{
    printf("In func1 ...n");
    long i = 0;
    while(1){
        i++;
        if(count == 1)
            break;
    }
    printf("The total number counted is: %ld n", i);
    count = 0;
    i = 0;
}

void func2(void * args)
{
    printf("In func2 ...n");
    waitFor(3);
    count = 1;
}


int main()
{
    pthread_t th1, th2;

    int j = 0;
    while(j++ < 4){
        printf("nRound:t%dn", j);

        pthread_create(&th1, NULL, (void*)func1,NULL);
        pthread_create(&th2, NULL, (void*)func2, NULL);

        pthread_join(th1,NULL);
        pthread_join(th2,NULL);
        waitFor(3);
    }

    return 0;
}

I've read various references and to my understanding pthread_join() means that if there are 2 or more threads, then they will wait for one thread to finish its execution and then next one will start executing and so on.

But when i run this program, the moment pthread_join(th1) is executed, both threads are created and executed 'concurrently'. How is this happening? Output:

Round:  1
In func2 ...
In func1 ...
The total number counted is: 897651254 

Round:  2
In func1 ...
In func2 ...
The total number counted is: 1051386065

........

My goal is to run these 2 threads in parallel. For now, join seems to do this; or am I going wrong somewhere?

And I've read that using volatile is not preferred for threads in C. So is there any way I could use count as a signal from thread 2 to 1?

Aucun commentaire:

Enregistrer un commentaire