Advertisement
sanpai

thread

Oct 11th, 2013
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.36 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <malloc.h>
  5.  
  6. struct range
  7. {
  8. int threadnumber;
  9. unsigned long start;
  10. unsigned long end ;
  11.  
  12. };
  13.  
  14. void * function(void *ptr)
  15. {
  16. struct range *rptr;
  17. rptr=(struct range *)ptr;
  18.  
  19. printf("\n Thread number: %d,start : %lu,end :%lu",rptr->threadnumber,rptr->start,rptr->end);
  20.  
  21. }
  22.  
  23. int main()
  24. {
  25. pthread_t *threadid;
  26.  
  27. int i,j,threadcount;
  28.  
  29. unsigned long start[3];
  30. unsigned long end[3];
  31.  
  32. struct range **Rangearr;
  33.  
  34. printf("\n Enter the number of threads to run : ");
  35. scanf("%d",&threadcount);
  36.  
  37. Rangearr=(struct range **)malloc(threadcount*sizeof(struct range *));
  38.  
  39. threadid=(pthread_t *)malloc(threadcount * sizeof(pthread_t) );
  40.  
  41. for(i=0;i<threadcount;i++)
  42. {
  43. start[i]=i;
  44. end[i]=i+3;
  45. threadid[i]=i;
  46.  
  47.  
  48. }
  49.  
  50.  
  51. for(i=0;i<threadcount;i++)
  52. {
  53. Rangearr[i]=(struct range *)malloc(sizeof(struct range));
  54. Rangearr[i]->start=start[i];
  55. Rangearr[i]->end=end[i];
  56. Rangearr[i]->threadnumber=i;
  57.  
  58.  
  59. }
  60.  
  61. for(i=0;i<threadcount;i++)
  62. {
  63. pthread_create(&threadid[i],NULL,function,(void *) Rangearr[i]);
  64. }
  65.  
  66.  
  67. for(j=0;j<threadcount;j++)
  68. {
  69. pthread_join(threadid[j], NULL);
  70. }
  71.  
  72. free( Rangearr);
  73. free(threadid);
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement