Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <unistd.h>
- #include <stdio.h>
- #include <termios.h>
- #include <fcntl.h>
- #include <sys/stat.h>
- #include <semaphore.h>
- #include <fstream>
- const int name_size = 10;
- const char sem_name[name_size] = "/LAB5";
- const char file_name[name_size] = "lab5.txt";
- std::ofstream file;
- struct argum
- {
- int fl = 0;
- sem_t* sem_id;
- };
- void* _thread(void* args)
- {
- char ch = '1';
- while(static_cast<argum*>(args)->fl != 1)
- {
- sem_wait(static_cast<argum*>(args)->sem_id);
- for (int i = 1; i < 5; ++i)
- {
- file << ch;
- file.flush();
- std::cout << ch;
- std::cout.flush();
- sleep(1);
- }
- sem_post(static_cast<argum*>(args)->sem_id);
- sleep(1);
- }
- auto code = new int;
- *code = 1;
- pthread_exit(code);
- }
- int main(int argc, char *argv[])
- {
- pthread_t id;
- void *ret;
- argum arguments;
- arguments.sem_id = sem_open(sem_name, O_CREAT, 0644, 1);
- std::cout << arguments.sem_id << '\n';
- file.open(file_name, std::ios_base::app);
- if(pthread_create(&id,NULL,_thread,&arguments))
- {
- return 1;
- }
- else
- {
- std::cout << "thread started \n";
- }
- std::cout << "system paused, press enter to continue\n";
- getchar();
- arguments.fl = 1;
- pthread_join(id, &ret);
- std::cout << "thread returned: " << *(int *)ret << "\n";
- delete (int *)ret;
- file.close();
- sem_close(arguments.sem_id);
- sem_unlink(sem_name);
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement