My program has to increment a counter strictly alternatively using 2 threads and synchronizing them using a pipe file. I know it doesn't really make sense but it's a university task. The problem works if I run it with CodeBlocks for instance but it doesn't print anything when I execute the program from linux terminal and I can't figure out why. Any idea? Here is my code:
#include <stdlib.h>
#include <pthread.h>
#include <wait.h>
#include <unistd.h>
#include <string.h>
int contor;
int fd[2];
void* thread_function(void* arg) {
int* th = (int*)arg;
char x = 'x';
while(1)
{
if (*th == 0 && contor % 2 == 0 && contor < 100) {
close(fd[0]);
write(fd[1], &x, 1);
contor ;
printf("Counter: %d incremented by thread: %ld\n", contor, pthread_self());
sleep(0);
if (contor >= 100)
{
pthread_exit(NULL);
}
} else if (*th == 1 && contor % 2 == 1 && contor < 100){
close(fd[1]);
read(fd[0], &x, 1);
contor ;
printf("Counter: %d incremented by thread: %ld\n", contor, pthread_self());
if (contor >= 100)
{
pthread_exit(NULL);
}
}
if (contor >= 100)
{
pthread_exit(NULL);
}
}
}
void main(int argc, char** argv) {
int tr1 = 0;
int tr2 = 0;
pthread_t t1, t2;
int th0 = 0;
pipe(fd);
tr1 = pthread_create(&t1, NULL, &thread_function, (void*)&th0);
if (tr1) {
printf("Error creating thread #1!");
}
int th1 = 1;
tr2 = pthread_create(&t2, NULL, &thread_function, (void*)&th1);
if (tr2) {
printf("Error creating thread #2!");
}
pthread_join(t1, NULL);
pthread_join(t2, NULL);
}
I compile the file using: gcc -o ex.exe ex.c -lpthread
I execute the executable using: ./ex.exe
CodePudding user response:
File descriptors are shared by all the threads of a process. One of your threads is closing one end of the pipe (fd[0]
) and writing the other end of the pipe (fd[1]
). Your other thread is closing the other end of the pipe (fd[1]
) and reading the other end of the pipe (fd[0]
). Also, they are being closed multiple times in a while
loop.
Getting rid of the close(fd[0])
and close(fd[1])
calls in thread_function
will help a bit. There may be other problems in thread_function
because the program stopped producing output after the counter reached the value 3
when I tried it.
Hint: Use two pipes.