Advertisement
EternalHaru

Untitled

May 28th, 2018
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include <iostream>
  6.  
  7. using namespace std;
  8.  
  9.  
  10. void* threadOne(void* flag){
  11.     void* counter = malloc(sizeof(int));
  12.     *(int*)counter = 0;
  13.     puts("threadOne started");
  14.     while (*reinterpret_cast<bool*>(flag)) {
  15.         puts("1");
  16.         (*(int*)counter)++;
  17.         sleep(1);
  18.     }
  19.     puts("threadOne finished");
  20.     pthread_exit(counter);
  21. }
  22.  
  23.  
  24. void* threadTwo(void* flag){
  25.     void* counter = malloc(sizeof(int));
  26.     *(int*)counter = 0;
  27.     puts("threadTwo started");
  28.     while (*reinterpret_cast<bool*>(flag)) {
  29.         puts("2");
  30.         (*(int*)counter)++;
  31.         sleep(1);
  32.     }
  33.     puts("threadTwo finished");
  34.     pthread_exit(counter);
  35. }
  36.  
  37.  
  38. int main(int argc, char** argv) {
  39.     pthread_t thread1;
  40.     pthread_t thread2;
  41.     bool flag1 = true;
  42.     bool flag2 = true;
  43.    
  44.     if(pthread_create(&thread1, NULL, threadOne, (void*)&flag1)){
  45.         return EXIT_FAILURE;
  46.     }
  47.    
  48.     if(pthread_create(&thread2, NULL, threadTwo, (void*)&flag2)){
  49.         return EXIT_FAILURE;
  50.     }
  51.    
  52.     getchar();
  53.    
  54.     flag1 = false;
  55.     flag2 = false;
  56.    
  57.     int *firstCounter = nullptr;
  58.     int *secondCounter = nullptr;
  59.    
  60.     if(pthread_join(thread1, (void**)&firstCounter)){
  61.         return EXIT_FAILURE;
  62.     }
  63.    
  64.     if(pthread_join(thread2, (void**)&secondCounter)){
  65.         return EXIT_FAILURE;
  66.     }
  67.    
  68.     cout<<*firstCounter<<endl;
  69.     cout<<*secondCounter<<endl;
  70.    
  71.     free(firstCounter);
  72.     free(secondCounter);
  73.    
  74.     return EXIT_SUCCESS;
  75. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement