Advertisement
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 <fcntl.h>
- #include <cstring>
- using namespace std;
- typedef struct Arguments {
- bool* flag;
- int *fd;
- } arguments;
- void* threadOne(void* args){
- arguments *argument = (arguments*) args;
- void* counter = malloc(sizeof(int));
- *(int*)counter = 0;
- puts("threadOne started");
- char string[] = "LETI 2018 OS";
- int y;
- while (*(argument->flag)) {
- write(argument->fd[1], string, (strlen(string)+1));
- printf("Writed\n");
- sleep(3);
- (*(int*)counter)++;
- }
- puts("threadOne finished");
- pthread_exit(counter);
- }
- void* threadTwo(void* args){
- arguments *argument = (arguments*) args;
- void* counter = malloc(sizeof(int));
- *(int*)counter = 0;
- puts("threadTwo started");
- char readbuffer[80];
- while (*(argument->flag)) {
- if(read(argument->fd[0], readbuffer, sizeof(readbuffer))==-1){
- puts("threadTwo's waiting for the record");
- sleep(3);
- (*(int*)counter)++;
- continue;
- } else {
- printf("Readed: ");
- puts(readbuffer);
- (*(int*)counter)++;
- sleep(3);
- }
- }
- puts("threadTwo finished");
- pthread_exit(counter);
- }
- int main(int argc, char** argv) {
- pthread_t thread1;
- pthread_t thread2;
- bool flag = true;
- arguments args;
- int* fd = new int[2];
- pipe(fd);
- fcntl(fd[0], F_SETFL, fcntl(fd[0], F_GETFL, 0) | O_NONBLOCK);
- args.flag = &flag;
- args.fd = fd;
- if(pthread_create(&thread1, NULL, threadOne, (void*)&args)){
- return EXIT_FAILURE;
- }
- if(pthread_create(&thread2, NULL, threadTwo, (void*)&args)){
- return EXIT_FAILURE;
- }
- getchar();
- flag = false;
- int *firstCounter = 0;
- int *secondCounter = 0;
- if(pthread_join(thread1, (void**)&firstCounter)){
- return EXIT_FAILURE;
- }
- if(pthread_join(thread2, (void**)&secondCounter)){
- return EXIT_FAILURE;
- }
- cout<<*firstCounter<<endl;
- cout<<*secondCounter<<endl;
- free(firstCounter);
- free(secondCounter);
- close(fd[0]);
- close(fd[1]);
- free(fd);
- return EXIT_SUCCESS;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement