Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <pthread.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <cstring>
- #include <fcntl.h>
- #include <fstream>
- #include <sys/types.h>
- #include <sys/ipc.h>
- #include <sys/sem.h>
- #include <semaphore.h>
- //структура для флага,названия файла,потока для работы с файлом и именованного семафора
- struct Args {
- int flag;
- char * fileName = "/home/dimka/text.txt";
- std::fstream myfile;
- sem_t *mutex;
- };
- void* func_1(void* args){
- Args *arg=(Args*) args;
- char input ='2';
- std::cout<<"Enter in critical sector"<<std::endl;
- while(arg->flag==0){
- //блокируем семафор
- sem_wait(arg->mutex);
- for (int i = 0; i < 5; ++i) {
- std::cout<<"Write in file:"<<input<<std::endl;
- //записываем в файл
- arg->myfile << input<<std::flush;
- sleep(1);
- }
- std::cout<<"Exit from critical sector"<<std::endl;
- //разблокируем семафор
- sem_post(arg->mutex);
- sleep(1);
- }
- }
- int main() {
- Args file;
- file.flag =0;
- //создаем семафор
- if ((file.mutex = sem_open("mysemaphor", O_CREAT, 0644, 1)) == SEM_FAILED) {
- perror("semaphore initilization");
- exit(1);
- }
- //открываем семафор
- file.myfile.open(file.fileName,std::fstream::app);
- pthread_t pthread_2;
- pthread_create(&pthread_2, NULL, func_1, (void*) &file);
- getchar();
- file.flag=1;
- pthread_join(pthread_2, nullptr);
- //закрываем файл
- file.myfile.close();
- //закрываем семафор
- sem_close(file.mutex);
- //удаляем семафор
- sem_unlink("mysemaphore");
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement