Dynamically allocating work to pthreads via a queue
Okay, so I'm having an issue with dynamically allocating work to pthreads in a queue.
For example, in my code I have a struct like below:
struct calc
{
d开发者_开发问答ouble num;
double calcVal;
};
I store each struct in an array of length l like below.
struct calc **calcArray;
/* then I initialize the calcArray to say length l and
fill each calc struct with a num*/
Now, based on num, I want to find the value of calcVal. Each struct calc has a different value for num.
I want to spawn 4 pthreads which is easy enough but I want to make it so at the start,
thread 0 gets calcArray[0]
thread 1 gets calcArray[1] thread 2 gets calcArray[2] thread 3 gets calcArray[3]Now assuming that it will take different times for each thread to do the calculations for each calc,
if thread 1 finishes first, it will then get calcArray[4]
then thread 3 finishes and gets calcArray[5] to do
and this continues until it reaches the end of calcArray[l].
I know I could just split the array into l/4 (each thread gets one quarter of the calcs) but I don't want to do this. Instead I want to make the work like a queue. Any ideas on how to do this?
You could accomplish it pretty easily, by creating a variable containing the index of the next element to be assigned, and then having it secured by a mutex.
Example:
// Index of next element to be worked on
int next_pos;
// Mutex that secures next_pos-access
pthread_mutex_t next_pos_lock;
int main() {
// ...
// Initialize the mutex before you create any threads
pthread_mutex_init(&next_pos_lock, NULL);
next_pos = NUM_THREADS;
// Create the threads
// ...
}
void *threadfunc(void *arg) {
int index = ...;
while (index < SIZE_OF_WORK_ARRAY) {
// Do your work
// Update your index
pthread_mutex_lock(&next_pos_lock);
index = next_pos;
next_pos++;
pthread_mutex_unlock(&next_pos_lock);
}
}
See also: POSIX Threads Programming - Mutex Variables
精彩评论