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;
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.