0

This below code is the code minimized of real code. Is posible synchronize a global variable with pthread and main while(1)? On the below code, the printf not apper in order and delayed of the 1 second.

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

pthread_mutex_t mutex1 = PTHREAD_MUTEX_INITIALIZER;
int teste;

void *ThreadFunc(void *arg)
{

    while (1)
    {
        pthread_mutex_lock( &mutex1 );
        if (teste++ > 3) teste = 0;
        pthread_mutex_unlock( &mutex1 );
        sleep(1);
    }

    return NULL;
}

int main(void)
{
    pthread_t thread;
    int teste_ant;

    pthread_create(&thread, NULL, ThreadFunc, NULL);

    while (1)
    {
        if (teste != teste_ant)
        switch (teste)
        {
            case 0:
                printf("Zero\n");
                break;

            case 1:
                printf("One\n");
                break;

            case 2:
                printf("Two\n");
                break;

            default:
                printf("Default\n");
        }

        teste_ant = teste;
    }

    return 0;
}
2
Contributors
1
Reply
3
Views
5 Years
Discussion Span
Last Post by L7Sqr
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.