EternalHaru

Untitled

May 28th, 2018
85
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.66 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <pthread.h>
  4. #include <unistd.h>
  5. #include <iostream>
  6. #include <semaphore.h>
  7. #include <fcntl.h>
  8.  
  9. using namespace std;
  10.  
  11.  
  12. typedef struct Arguments {
  13.     bool* flag;
  14.     sem_t* sem;
  15.     FILE* file;
  16. } arguments;
  17.  
  18.  
  19. void* thread(void* args){
  20.     arguments *argument = (arguments*) args;
  21.     void* counter = malloc(sizeof(int));
  22.     *(int*)counter = 0;
  23.     puts("thread started");
  24.     while (*(argument->flag)) {
  25.         sem_wait(argument->sem);
  26.         for(int i = 0; i < 3; i++){
  27.             fputs("1", argument->file);
  28.             fflush(argument->file);
  29.         }
  30.         sem_post(argument->sem);
  31.         (*(int*)counter)++;
  32.         sleep(1);
  33.     }
  34.     puts("thread finished");
  35.     pthread_exit(counter);
  36. }
  37.  
  38.  
  39.  
  40. int main(int argc, char** argv) {
  41.     sem_t* namedSemaphore;
  42.     FILE* file;
  43.     pthread_t threadInit;
  44.     bool flag = true;
  45.     arguments args;
  46.    
  47.     char semaphoreName[] = "rng1";
  48.     char pathToFile [] = "file.txt";
  49.    
  50.     sem_unlink(semaphoreName);
  51.    
  52.     namedSemaphore = sem_open(semaphoreName, O_CREAT, 0644, 1);
  53.    
  54.     file = fopen(pathToFile,"a");
  55.    
  56.     args.flag = &flag;
  57.     args.sem = namedSemaphore;
  58.     args.file = file;
  59.  
  60.    
  61.     if(pthread_create(&threadInit, NULL, thread, (void*)&args)){
  62.         return EXIT_FAILURE;
  63.     }
  64.        
  65.     getchar();
  66.    
  67.     flag = false;
  68.    
  69.     int *counter = 0;
  70.    
  71.     if(pthread_join(threadInit, (void**)&counter)){
  72.         return EXIT_FAILURE;
  73.     }
  74.    
  75.     cout<<*counter<<endl;
  76.    
  77.     sem_close(namedSemaphore);
  78.     fclose(file);
  79.     sem_unlink(semaphoreName);
  80.     return EXIT_SUCCESS;
  81. }
Advertisement
Add Comment
Please, Sign In to add comment