Differentiate between threads called by pthread

355 Views Asked by At

A supplied framework is calling my function PartialCodec.

pthread_create(&(pcPthread[iTd]),NULL,PartialCodec,(void *)&pcMCData[iTd]);

I am not allowed to change the framework code. However, inside PartialCodec I want to assign different tasks for different threads and so I need to differentiate between each thread. How can I do this?

2

There are 2 best solutions below

5
On BEST ANSWER

Use the argument, Luke.

You're passing &pcMCData[iTd] as the thread argument.

So just add some fields to that structure, telling the thread which tasks to work on. (And obviously set those fields before creating the thread)

pcMCData[iTd].thingToWorkOn = /* however you decide the thing to work on */;
pthread_create(&(pcPthread[iTd],NULL,PartialCodec,(void *)&pcMCData[iTd]);
0
On

Assuming you know how many threads will be calling PartialCodec, you can use static variables within the function to facilitate communication between threads. A bare static would allow all threads in PartialCodec to manipulate the same object instance.

void * PartialCodec (void *arg) {
    static pthread_mutex_t lock = PTHREAD_MUTEX_INITIALIZER;
    static struct state {
        /* some state */
    } critical;
    struct state local;

    pthread_mutex_lock(&lock);
    local = critical; /* make a local copy */
    /* update critical */
    pthread_mutex_unlock(&lock); 

    /* ... refer to local copy of state ... */
}

The critical state tracks which part of the problem a particular thread should solve. Copying it to local establishes that the thread will work on that part of the problem. The critical state is then updated so the next thread that reads critical will know to work on a different part of the problem.