Guest User

Untitled

a guest
Jul 17th, 2018
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.56 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <iostream>
  5. #include <queue>
  6. using namespace std;
  7.  
  8. #define NUM_THREADS 15
  9. #define MAX_LOTTO 999999
  10.  
  11. // global variables
  12. int lotto_count=0;
  13. queue<int> tqueue;
  14.  
  15. pthread_mutex_t count_mutex = PTHREAD_MUTEX_INITIALIZER;
  16.  
  17. void *thread_work( void * tid );
  18.  
  19. int main( int argc, char * argv[] ){
  20. pthread_t threads[NUM_THREADS];
  21. int status, i;
  22. int count=0;
  23.  
  24. for( i=0; i < NUM_THREADS; i++ ){
  25. cout << "Main program. Creating thread " << i << endl;
  26. tqueue.push( i );
  27. status = pthread_create(&threads[i], NULL, thread_work, (void *)i);
  28.  
  29. if( status != 0 ){
  30. printf("Couldn't create thread error code %d0", status );
  31. exit(-1);
  32. }
  33. }
  34. while( lotto_count < MAX_LOTTO ) ;
  35. //cout << count << " number" << endl;
  36. //exit(NULL);
  37. return 0;
  38. }
  39.  
  40. // Function that is ran by each thread to access shared data
  41. void *thread_work( void * tid ){
  42. int tickets=0; // number of tickets this thread 'bought'
  43. int skip=0; // Add some variation to the mix
  44. int thread_id = (int)tid;
  45. while( lotto_count < MAX_LOTTO ){
  46. /*
  47. if( tqueue.front() == thread_id ){
  48. cout << thread_id << " got number " << lotto_count << endl;
  49. lotto_count++;
  50. tqueue.pop();
  51. tqueue.push( thread_id );
  52. }
  53. */
  54. if( skip == 0 ){
  55. pthread_mutex_lock( &count_mutex );
  56. skip = 1;
  57. tickets++;
  58. lotto_count++;
  59. pthread_mutex_unlock( &count_mutex );
  60. } else {
  61. skip = 0;
  62. }
  63. }
  64. cout << "[ " << thread_id << " ] bought " << tickets << endl;
  65. pthread_exit(NULL);
  66. }
Add Comment
Please, Sign In to add comment