My program contains two threads for which they are expected to end. I use a single variable that is shared between threads and this is x
and a single mutex.
The q
key ends the thread
Problems I want to solve:
- I want the stars (
*
) that are displayed one by one on the line now, I want them to be one after the other on the same line - I don't want to have to press enter after
q
to exit the program. I want it to exit the program immediately when I pressq
(no additional keys)
What should I change?
P.S (I have two warnings when running the program with gcc program.c -o program -lpthread
, but that's not what I'm interested in at the moment, I'll solve it later)
program.c: In function ‘first’:
program.c:24:1: warning: control reaches end of non-void function [-Wreturn-type]
24 | }
| ^
program.c: In function ‘second’:
program.c:44:1: warning: control reaches end of non-void function [-Wreturn-type]
44 | }
| ^
code:
#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <sys/time.h>
pthread_mutex_t mut = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond_q = PTHREAD_COND_INITIALIZER;
char *x;
void *first(void *arg) {
x = (char*)malloc(sizeof(char));
do {
scanf("%c", x);
pthread_mutex_lock(&mut);
if(x[0] == 'q') {
pthread_cond_signal(&cond_q);
}
pthread_mutex_unlock(&mut);
} while( x[0] != 'q');
free(x);
printf("exited thread 1\n");
}
void *second(void *arg) {
struct timespec ts;
int ok = 1;
pthread_mutex_lock(&mut);
while(ok) {
clock_gettime(CLOCK_REALTIME, &ts);
ts.tv_sec += 1;
ok = pthread_cond_timedwait(&cond_q, &mut, &ts);
if(ok == 0) break;
printf("*\n");
}
pthread_mutex_unlock(&mut);
printf("exited thread 2\n");
}
int main()
{
pthread_t read;
pthread_t write;
pthread_create(&read, NULL, &first,NULL);
pthread_create(&write, NULL, &second,NULL);
pthread_join(read, NULL);
pthread_join(write, NULL);
pthread_cond_destroy(&cond_q);
pthread_mutex_destroy(&mut);
return 0;
}