Mario Camia
Mario Camia

Reputation: 113

how I can create a timer that works simultaneously with a game in C?

I am creating a game called "Point and Fame", which is based on a combination of numbers to guess that the compiler extracts it random, I have to add a timer that will print at the same time the game is running, I have understood that i need to create a multithread process which i don't know how to do it.

If there's another way to put the timer in the game, or make to loops run at the same time will help me a lot.

Upvotes: 2

Views: 359

Answers (1)

StackFlowed
StackFlowed

Reputation: 6816

I had read this article before don't know if it will help but just check this

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

/* This is our thread function.  It is like main(), but for a thread */
void *threadFunc(void *arg)
{
    char *str;
    int i = 0;

    str=(char*)arg;

    while(i < 10 )
    {
        usleep(1);
        printf("threadFunc says: %s\n",str);
        ++i;
    }

    return NULL;
}

int main(void)
{    
    pthread_t pth;  // this is our thread identifier
    int i = 0;

    /* Create worker thread */
    pthread_create(&pth,NULL,threadFunc,"processing...");

    /* wait for our thread to finish before continuing */
    pthread_join(pth, NULL /* void ** return value could go here */);

    while(i < 10 )
    {
        usleep(1);
        printf("main() is running...\n");
        ++i;
    }

    return 0;
}

Upvotes: 1

Related Questions