Simple pthreads question

I'm trying to parallelize a simple task using pthreads but I'm not entirely sure how to do the implementation. My problem is that I have n vectors of length L, on each of which I need to compute something that takes O(L) time, and both n and L are large, so I think it's in my best interest to parallelize. Unfortunately I am on a shared server and I believe that many other people would be quite upset with me if I created n threads and took up all the CPUs, so I'd like to do something like define a fixed number of threads that I can use and then have something like:

1
2
3
4
5
6
7
for (i = 0; i < n; i++) {
	if (threads are available) {
		pthread_create(...)
	} else {
		wait for a thread to finish then start
	}
}


Unfortunately I have no idea how to do this.
(Queue is a thread-safe queue type.)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
void thread(Queue<job> *q){
    while (!q->empty()){
        job j=q->pop();
        function(*j.vector);
    }
}

//in main
    Queue<job> queue;
    for (int i=0;i<n;i++){
        job j;
        j.vector=&vectors[i];
        queue.push(j);
    }
    Thread threads[MAX_THREADS];
    for (int i=0;i<MAX_THREADS;i++)
        threads.start(thread,&queue);
    for (int i=0;i<MAX_THREADS;i++)
        threads.join();
Topic archived. No new replies allowed.