laroy
laroy

Reputation: 153

How To Verify Thread Creation (C-Program)

I'm creating a program that will require n-specified threads that will each act as a "mole" (I'm making whack-a-mole). Now.. I think I have something that does that, but I'm not convinced that my print statements actually verify that I have n-different threads... how exactly can I know that this has worked?

my code is as follows:

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

int k = 0;

void* thread_function()
{
    k++;
    printf("Mole #%d\n", k);
}

int main(int argc,char *argv[])
{
    int mole_count= atoi(argv[1]);
    pthread_t thread_id[mole_count];
    int i;

    for(i=0;i<mole_count;i++)
    {
        pthread_create (&thread_id[i], NULL , &thread_function, NULL);

    }  

    for(i=0;i<mole_count;i++){
        pthread_join(thread_id[i],NULL);   
    }

    return 0;
}

Thanks

Upvotes: 0

Views: 1327

Answers (1)

gavinb
gavinb

Reputation: 20048

The pthread_create() function will return 0 on success, so you know whether or not the thread was successfully created. (What happens after that depends on the thread function itself, obviously.)

Every thread within a process has a unique ID associated with it (just as all processes in the OS have a unique process iD). You can query the ID of the thread by calling pthread_t pthread_self(). So you could print out this arbitrary but unique value in each thread function, showing you each different thread running.

Note that your counter k is shared, but is not protected by a mutex. Since it is updated (read-modify-update) in each thread, there is the potential for race condition and thus buggy behaviour. Use an atomic variable to avoid these problems.

Also, your thread function should return NULL since it has the return type of void*.

Now having explained all that, I'm not sure that a "whack-a-mole" game is a good candidate for multiple threads. Threads can be very useful, but bring with them complexities of their own. For example, how do you communicate between threads, maintain shared state, and coordinate events? Threads can also make debugging significantly more difficult. Consider a simpler design with a round-robin approach to begin with.

Upvotes: 1

Related Questions