Advertisement
Guest User

Untitled

a guest
Feb 21st, 2018
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.74 KB | None | 0 0
  1. #include <pthread.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. #define NUM_THREADS 4
  6.  
  7. typedef struct {
  8. const char* userInput;
  9. }sharedValue;
  10.  
  11. sharedValue globalVar;
  12.  
  13. void* threadListen(void* threadID){
  14. printf("thread %d live\n", threadID);
  15.  
  16. return 0;
  17. }
  18.  
  19. void* printText(void* foo){
  20.  
  21.  
  22.  
  23. while(globalVar.userInput == NULL){
  24. //Wait...
  25. }
  26.  
  27. printf("Thread received text: %s\n", globalVar.userInput);
  28.  
  29. return 0;
  30. }
  31.  
  32.  
  33. void* mainThread(void* foo){
  34.  
  35. pthread_t threads[NUM_THREADS];
  36. int rc, i;
  37.  
  38. for(i = 0; i<NUM_THREADS;i++){
  39.  
  40. //Printing Thread
  41. if(i == 3)
  42. rc = pthread_create(&threads[i], NULL, printText, (void *)i);
  43.  
  44. //Consumer Threads
  45. else
  46. rc = pthread_create(&threads[i], NULL, threadListen, (void *)i);
  47. }
  48.  
  49.  
  50. if(rc){
  51. printf("pthread_create ERROR");
  52. return -1;
  53. }
  54.  
  55. printf("Please enter text: ");
  56. char textEntered[100];
  57. scanf("%99[^\r\n]", textEntered);
  58.  
  59. //printf("%s", textEntered);
  60. globalVar.userInput = textEntered;
  61.  
  62. for (i = 0; i < NUM_THREADS; i++) {
  63. pthread_join(threads[i], NULL);
  64. }
  65.  
  66. return 0;
  67. }
  68.  
  69. int main(int argc, const char* argv[]){
  70.  
  71. int rc;
  72.  
  73. pthread_t main_thread;
  74.  
  75. //Producer Thread(Main Thread)
  76. rc = pthread_create(&main_thread, NULL, mainThread, NULL);
  77.  
  78. if(rc){
  79. printf("pthread_create ERROR");
  80. return -1;
  81. }
  82.  
  83. pthread_join(main_thread, NULL);
  84.  
  85. return 0;
  86. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement