Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #define _POSIX_C_SOURCE 200809L
- #include <ncurses.h>
- #include <pthread.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <assert.h>
- #include <stdlib.h>
- #include <errno.h>
- #define CUBE_LENGTH 12
- #define NUM_THREADS 2
- #define test_errno(msg) do{if (errno) {perror(msg); exit(EXIT_FAILURE);}} while(0);
- pthread_mutex_t blokada;
- void* perform_work(void* argument) {
- int passed_in_value;
- int counter = 0;
- passed_in_value = *((int*) argument);
- // printf("Hello World! It's me, thread with argument %d!\n", passed_in_value);
- int y=2*CUBE_LENGTH,x=2*CUBE_LENGTH;
- int y_,x_;
- // const char * z="O",* r=" ";
- char z='O',r=' ';
- if (passed_in_value==0){ x_=-1; y_=-1; }
- else if(passed_in_value==1){ x_=-2; y_=-1; }
- else if(passed_in_value==2){ x_=-1; y_=-2; }
- else {mvprintw(CUBE_LENGTH+2, 0, "Error, program gives wrong direction\n" ); }
- mvaddch(y, x, z);
- refresh();
- bool first=true;
- while(counter<5)
- {
- // #ifdef BLOKADA
- errno = pthread_mutex_lock(&blokada);
- test_errno("pthread_mutex_lock");
- // #endif
- mvaddch(y, x, z);
- refresh();
- sleep(1);
- mvaddch(y, x, r);
- refresh();
- sleep(1);
- // #ifdef BLOKADA
- errno = pthread_mutex_unlock(&blokada);
- test_errno("pthread_mutex_unlock");
- // #endif
- if(!first){
- //if((x==CUBE_LENGTH && y==CUBE_LENGTH+1) || (x==CUBE_LENGTH+1 && y==2*CUBE_LENGTH) || (x==2*CUBE_LENGTH+1 && y==CUBE_LENGTH) || (x==2*CUBE_LENGTH+1 && y==2*CUBE_LENGTH))
- //{x_*=-1; y_*=-1;counter++;} //na to nie patrzcie ^
- if(x==CUBE_LENGTH || x==2*CUBE_LENGTH){ x_*=-1; counter++;}
- if(y==CUBE_LENGTH || y==2*CUBE_LENGTH){ y_*=-1; counter++;}
- }else first=false;
- x+=x_; y+=y_;
- }
- return NULL;
- }
- int main(int argc, char** argv) {
- pthread_t threads[NUM_THREADS];
- int thread_args[NUM_THREADS];
- int result_code;
- unsigned index;
- const char * ramka="+";
- initscr();
- int i,j;
- for(i=CUBE_LENGTH-1;i<=2*CUBE_LENGTH+1;i++) for(j=CUBE_LENGTH-1;j<=2*CUBE_LENGTH+1;j++)
- {
- if(i==CUBE_LENGTH-1 || j== CUBE_LENGTH-1 || i==2*CUBE_LENGTH+1 || j==2*CUBE_LENGTH+1) mvprintw(j, i, ramka);
- refresh();
- }
- errno = pthread_mutex_init(&blokada, NULL);
- test_errno("pthread_mutex_init");
- for (index = 0; index < NUM_THREADS; ++index) {
- thread_args[ index ] = index%3;
- // result_code = pthread_create(&threads[index], NULL, perform_work, &thread_args[index]);
- errno = pthread_create(&threads[index], NULL, perform_work, &thread_args[index]);
- // assert(!result_code);
- test_errno("pthread_create");
- }
- for (index = 0; index < NUM_THREADS; ++index) {
- // result_code = pthread_join(threads[index], NULL);
- // assert(!result_code);
- errno = pthread_join(threads[index], NULL);
- test_errno("pthread_join");
- }
- endwin();
- printf("In main: All threads completed successfully\n");
- exit(EXIT_SUCCESS);
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement