Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
563 views
in Technique[技术] by (71.8m points)

c - How can I pass the index of a for loop as the argument for pthread_create

I am using a for loop to create a number of threads and passing the index i as an argument as follows:

pthread_t p[count];
for (int i = 0; i < count; i++){
    pthread_create(&p[i], NULL, &somefunc, (void*)&i);
}

Then I attempt to retrieve the value of i:

void *somefunc (void* ptr){
    int id = *(int*)ptr;
}

However, I noticed that sometimes, id in the threads will have overlapping values which I suspect is due to the index of the for loop updating before the thread is able to retrieve the value (since I passed in the pointer, as opposed to the value itself). Does anyone have any suggestions to overcome this issue without slowing down the for loop?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

This is happening because once you pass a pointer to i you now have multiple threads using the same value. This causes a data race because the first thread is modifying i and your second thread is expecting it to never change. You can always allocate a temporary int and pass it to the thread function.

pthread_create(&p[i], NULL, &somefunc, new int(i));

This will allocate an integer in dynamic storage (heap) and initialize it with the value of i. A pointer to the newly allocated integer will then be passed to the thread function.

Then in the thread function you can take the value passed as you already do and then delete the int object.

void *somefunc (void* ptr){
    int id = *(int*)ptr;
    delete (int*)ptr;
}

[Suggestion: Avoid C style casts.]


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...