Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <unistd.h>
- #include <iostream>
- #include <semaphore.h>
- #include <fcntl.h>
- using namespace std;
- typedef struct Arguments {
- bool* flag;
- sem_t* sem;
- FILE* file;
- } arguments;
- void* thread(void* args){
- arguments *argument = (arguments*) args;
- void* counter = malloc(sizeof(int));
- *(int*)counter = 0;
- puts("thread started");
- while (*(argument->flag)) {
- sem_wait(argument->sem);
- for(int i = 0; i < 3; i++){
- fputs("1", argument->file);
- fflush(argument->file);
- }
- sem_post(argument->sem);
- (*(int*)counter)++;
- sleep(1);
- }
- puts("thread finished");
- pthread_exit(counter);
- }
- int main(int argc, char** argv) {
- sem_t* namedSemaphore;
- FILE* file;
- pthread_t threadInit;
- bool flag = true;
- arguments args;
- char semaphoreName[] = "rng1";
- char pathToFile [] = "file.txt";
- sem_unlink(semaphoreName);
- namedSemaphore = sem_open(semaphoreName, O_CREAT, 0644, 1);
- file = fopen(pathToFile,"a");
- args.flag = &flag;
- args.sem = namedSemaphore;
- args.file = file;
- if(pthread_create(&threadInit, NULL, thread, (void*)&args)){
- return EXIT_FAILURE;
- }
- getchar();
- flag = false;
- int *counter = 0;
- if(pthread_join(threadInit, (void**)&counter)){
- return EXIT_FAILURE;
- }
- cout<<*counter<<endl;
- sem_close(namedSemaphore);
- fclose(file);
- sem_unlink(semaphoreName);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment