in His Steps
in His Steps

Reputation: 3245

'arg' in pthread_create in linux

I have an struct that I want to pass in pthread_create function

For ex.

typedef struct INFO
{
    int signal;
    int group_id;
}info_type;

struct ARG
{
    info_type *info;
    int id;
};

int i;
static info_type info; //skipped how name and signal is initialized
struct ARG args[5];
for ( i = 0; i < 5; ++i)
{
    args[i]->info = info;
    id = i;
}

Then, I am trying to create a thread that takes ARG pointer as 'arg'

start routine is like

void task(struct ARG * arg)
{
    while(arg->info->signal)
    {
        wait(arg->info->signal); // this part is just pseudo code (just waiting for sig)
    }

    // do some works
}

//this is pseudo code and assume pthread and attr are defined somewhere else 
pthread(pthread, attr, task, &arg[0]);

So, there are multiple args but sharing only one info_type, same group_id and signal. There is only one task routine which I want it to handle as shared signal is changed.

Then my question is:

Does arg passed into pthread function matters in order to check signal is changed? If signal is changed in another index for ex arg[3], will this be checked in task thread or does it not get recognized at all?

And since 'id' in each ARG will be necessary. Then if args[3] changed signal (arg[3] id necssary), will this task use arg[3]?

Or will it use whatever arg param was passed when I called pthread_create funciton?

Upvotes: 0

Views: 323

Answers (2)

user4815162342
user4815162342

Reputation: 155046

Memory is shared by all threads, so if you change arg->info->signal in one thread, the change will be seen by all threads.

However, when accessing such a shared resource, be sure to protect it with a mutex or a read-write lock. This prevents it from being modified by two threads at once, and also enforces a memory barrier to ensures that other writes are not reordered (which would cause them remain unseen by other threads).

Upvotes: 1

abligh
abligh

Reputation: 25129

I'm afraid your example doesn't make much sense (no pthread_create - is that meant to be the last line), and I don't fully understand your question. arg itself has nothing to do with signals.

However, I can tell you about the arg parameter. It contains an opaque pointer. What is meant by opaque is that only your code will look at it. pthread_create will simply pass it to the function you pass as the third parameter (start_routine). Whether it matters depends solely on what you use it for.

Upvotes: 0

Related Questions