Reputation: 11
I am trying to learn programming with pthreads and here is a problem that I am trying to solve. I have an array with lets say 10 inputs, and I have 3 threads, I want each thread to read one item from the array, until the array gets exhausted.
int arr[10] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
I would like the 3 threads to work as follows:
T1 T2 T3 T1 T2
10 11 12 13 14
What I have tried is, I have taken 3 sempahores, one for each thread and initialized the first one with 1 and the other with 0, as soon as we create the threads all the threads will try to get their semaphores, the two threads that have sem value initialized to 0 will have to wait, the one with value 1 will get to do the work. Once the first one is done, it would post to the second one, and when second one is done it will signal the third and so on until all the elements in the array are traversed.
However, when I try to run the following program, it segfaults. I am not sure what is going on. Can some one please give me some pointers as to what I am doing wrong. The code that I have written is shown below.
//Read one element using one thread
#include<pthread.h>
#include <semaphore.h>
#include <iostream>
using namespace std;
int arr[10] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 };
sem_t sem[3];
int count = 0;
void * printNumbers( void * arg ) {
while(1) {
sem_wait( &sem[count] );
cout<< " Waiting on the semaphore number " << count << endl;
count += 1;
if( count > 9 )
break;
cout<< " consuming " << arr[count]<< " with thid " << * ( (int*) arg ) << endl;
int nextPost = count % 3;
cout<< " Posting to semaphore number " << nextPost << endl;
sem_post( &sem[nextPost] );
}
}
int main() {
sem_init( &sem[0], NULL, 1 );
sem_init( &sem[1], NULL, 0 );
sem_init( &sem[2], NULL, 0 );
int t1 = 0;
int t2 = 1;
int t3 = 2;
pthread_t thid[3];
pthread_create( &thid[0], NULL, printNumbers, &t1 );
pthread_create( &thid[1], NULL, printNumbers, &t2 );
pthread_create( &thid[2], NULL, printNumbers, &t3 );
pthread_exit( 0 );
return 0;
}
Upvotes: 1
Views: 46
Reputation: 1526
When count
is bigger than 2, this will fail:
sem_wait( &sem[count] );
Apart from that you seem to misunderstand what threads are for. Threads are used to perform calculations in parallel. You effectively synchronize them to run one after another gaining nothing but additional problems.
Upvotes: 2