#include <pthread.h>
#include <stdio.h>
#define WIDTH 1000
#define HEIGHT 1000
typedef struct s_pair
{
int x;
int y;
} t_pair;
char pixels[HEIGHT][WIDTH];
void *add_to_global(void *param)
{
t_pair *input;
input = (t_pair *)param;
if (!(input->x % 2))
pixels[input->y][input->x] = '.';
else if (!(input->x % 3))
pixels[input->y][input->x] = '#';
else
pixels[input->y][input->x] = ' ';
return (NULL);
}
void thread_runner(int x_start, int x_end, int y_start, int y_end)
{
pthread_t workers[10];
t_pair inputs[10];
int i, x, y;
y = y_start - 1;
while (++y < y_end)
{
x = x_start - 1;
i = -1;
while (x < x_end)
{
if (++i < 10)
{
inputs[i] = (t_pair){++x, y};
pthread_create(&workers[i], NULL, add_to_global, (void *)&inputs[i]);
}
else
while (--i > -1)
pthread_join(workers[i], NULL);
}
while (--i > -1)
pthread_join(workers[i], NULL);
printf("%s\n", pixels[y]); // if this is removed, this program will never finish
}
}
int main()
{
thread_runner(0, WIDTH, 0, HEIGHT);
return (0);
}
So originally while trying to make a fractal visualizer I ran into this problem where I could use this method of running ten threads at a time only if I drew the image on the screen while doing it. If I instead let the program run by itself, it became completely unresponsive and my mac began making a disturbing noise. I'm still new to threads so this might be something very simple I've misunderstood about them.
This program is my attempt at reproducing the phenomenon without the need of all the fractal nonsense. It is a completely meaningless program that simply tells you whether the x-coordinate of a point is divisible by 2 or 3 and prints certain characters to the terminal accordingly.
If you remove the printf which prints each line y after it has processed each point x on that line, the program will become unresponsive. However, running the program with this periodic printing makes it work. This just seems like some programming-demons are playing tricks with me and making the problem undebuggable.
Why is this problem fixed by a seemingly meaningless printf? Why is my mac making a disturbing sound when I run it without this printf?