Advertisement
HimikoWerckmeister

Untitled

Mar 5th, 2016
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.80 KB | None | 0 0
  1. #define _GNU_SOURCE
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <pthread.h>
  5. #include <time.h>
  6. #include <unistd.h>
  7.  
  8. #define DATA_SIZE ((int) 100)
  9. #define NUM_THREADS ((int) 40)
  10. #define NUM_SWAPS ((int) 2000000)
  11.  
  12. int data[DATA_SIZE];
  13.  
  14. void *B(void *arg)
  15. {
  16. sleep(1);
  17. int *instancount=(int*)malloc(sizeof(int)*DATA_SIZE);
  18. for(int i=0;i<DATA_SIZE;i++)
  19. {
  20.  
  21. instancecount[i]=0;
  22. }
  23. int *limitptr = (int*)arg;
  24. int limit=*limitptr;
  25. for(int i=0;i<limit;i++)
  26. {
  27. instancecount[data[i]]++;
  28. }
  29. }
  30.  
  31. //check that each number from 0 to n occurs exactly once in the array
  32. pthread_t DataSpawn()
  33. {
  34. int i=DATA_SIZE;
  35. pthread_t tid;
  36. pthread_attr_t attr;
  37. pthread_attr_init(&attr);
  38. pthread_create(&tid,&attr,B,&i);
  39. //pthread_join(tid,NULL);
  40. return tid;
  41. }
  42.  
  43. void swap(int *a, int *b)
  44. {
  45. int temp;
  46. temp = *a;
  47. *a = *b;
  48. *b = temp;
  49.  
  50. }
  51.  
  52. void ZeroInit()// to do: change this name later
  53. {
  54. for(int i=0;(i+3)<=DATA_SIZE+2;i++)
  55. {
  56. data[i]=i;
  57. }
  58. }
  59.  
  60. void* A(void *arg)//
  61. {
  62. int *limitptr = (int*)arg;
  63. int limit=*limitptr;
  64. int idx1=0;
  65. int idx2=0;
  66. //srand(time(NULL));
  67. for(int i=0;i<limit;i++)
  68. {
  69. idx1= rand()%NUM_THREADS;
  70. idx2= rand()%NUM_THREADS;
  71. swap(&data[idx1],&data[idx2]);
  72. }
  73. //return 0;
  74. pthread_exit(0);
  75. }
  76.  
  77.  
  78.  
  79. void SpawnThreads(unsigned int n)
  80. {
  81.  
  82. int iNumThreads = n;
  83. int ret=-1;
  84. int ii=NUM_THREADS;
  85. pthread_t *threadArray=malloc(sizeof(pthread_t)*iNumThreads);
  86. pthread_t id;
  87. for(int i=0;i<iNumThreads;i++)
  88. {
  89. ret=pthread_create(&threadArray[i],NULL,A,&ii);
  90. if(ret != 0)
  91. {
  92. printf("Pthread error");
  93. }
  94.  
  95. }
  96. id = DataSpawn();
  97. for(int i=0;i<iNumThreads;i++)
  98. {
  99. pthread_join(threadArray[i],NULL);
  100. }
  101. pthread_cancel(id);
  102. pthread_join(id,NULL);
  103. }
  104.  
  105.  
  106.  
  107.  
  108.  
  109. int main(int argc, char **argv)
  110. {
  111.  
  112. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement