Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- #include <queue>
- using namespace std;
- #define NUM_THREADS 15
- #define MAX_LOTTO 999999
- // global variables
- int lotto_count=0;
- queue<int> tqueue;
- pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
- void *thread_work( void * tid );
- int main( int argc, char * argv[] ){
- pthread_t threads[NUM_THREADS];
- int status, i;
- int count=0;
- for( i=0; i < NUM_THREADS; i++ ){
- cout << "Main program. Creating thread " << i << endl;
- tqueue.push( i );
- status = pthread_create(&threads[i], NULL, thread_work, (void *)i);
- if( status != 0 ){
- printf("Couldn't create thread error code %d0", status );
- exit(-1);
- }
- }
- while( lotto_count < MAX_LOTTO ) ;
- //cout << count << " number" << endl;
- //exit(NULL);
- return 0;
- }
- // Function that is ran by each thread to access shared data
- void *thread_work( void * tid ){
- int tickets=0; // number of tickets this thread 'bought'
- int skip=0; // Add some variation to the mix
- int thread_id = (int)tid;
- while( lotto_count < MAX_LOTTO ){
- /*
- if( tqueue.front() == thread_id ){
- cout << thread_id << " got number " << lotto_count << endl;
- lotto_count++;
- tqueue.pop();
- tqueue.push( thread_id );
- }
- */
- if( skip == 0 ){
- pthread_mutex_lock( &count_mutex );
- skip = 1;
- tickets++;
- lotto_count++;
- pthread_mutex_unlock( &count_mutex );
- } else {
- skip = 0;
- }
- }
- cout << "[ " << thread_id << " ] bought " << tickets << endl;
- pthread_exit(NULL);
- }
Add Comment
Please, Sign In to add comment