首页 > 解决方案 > 多线程实现使用 2 个线程读取、旋转和保存图像

问题描述

我编写了这个程序,它应该使用两个线程,一个将图像读入缓冲区,第二个将图像旋转 90 度并将其保存到文件中。我需要运行几分钟并收集一些数据。我的问题是代码在没有 while 循环计数器的情况下运行正常,但我多次运行时遇到问题。我认为问题出在我的线程实现上。当包含 while 循环时,输出图像只是一组垂直线,而没有正确重建 while 计数器图像。谢谢你

我编写了这个程序,它应该使用两个线程,一个将图像读入缓冲区,第二个将图像旋转 90 度并将其保存到文件中。我需要运行几分钟并收集一些数据。我的问题是,如果没有 while 循环计数器,问题运行正常,但我多次运行时遇到问题。我认为问题出在我的线程实现上。谢谢你

#include <stddef.h>
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#define WIDTH 512
#define HEIGHT 512
#define DEPTH 255

pthread_mutex_t mtx;
static const unsigned MAX = 8;
char *buffer = (char *)malloc((MAX) * sizeof(char));

void *grab(void *buffer)
{
FILE *infile;
size_t i;

pthread_mutex_lock(&mtx);
char *localbuffer = (char *)buffer;
infile = fopen("lena512.pgm", "r");

for (i = 0; i < 4; ++i)
    fscanf(infile, "%*[^\n]\n");
//buffer = (char *)malloc((WIDTH/64) * sizeof(char));
//buffer = (char *)malloc((512) * sizeof(char)); /

for (i = 0; i < HEIGHT; ++i)
{
    fread(&localbuffer[i * WIDTH], sizeof(char),
          WIDTH, infile);
}
pthread_mutex_unlock(&mtx);
//fclose(infile);
//return localbuffer;
pthread_exit(NULL);
}

void *analyze(void *buffer)
{
pthread_mutex_lock(&mtx);
char *localbuffer = (char *)buffer;
FILE *outfile;
size_t i;
char *analyzed =
    (char *)malloc(WIDTH * HEIGHT * sizeof(char));

for (int x = 0; x < WIDTH; x++)
{
    for (int y = 0; y < HEIGHT; y++)
    {
        int offset = HEIGHT * x + y;
        analyzed[offset] = localbuffer[y * HEIGHT - 1 + x];
    }
}
outfile = fopen("analyzed.pgm", "w");
fputs("P5\n", outfile);
fprintf(outfile, "%d %d\n%d\n", WIDTH, HEIGHT, DEPTH);

for (i = 0; i < HEIGHT; ++i)
{
    fwrite(&analyzed[i * WIDTH], sizeof(char),
           WIDTH, outfile);
}
pthread_mutex_unlock(&mtx);
//fclose(outfile);
free(analyzed);
//return localbuffer;
pthread_exit(NULL);
}

int main(void)
{
char *localbuffer;
pthread_t thread1, thread2;
int counter = 10000;

while (counter != 0)
{

    pthread_create(&thread1, NULL, grab, buffer);
    pthread_create(&thread2, NULL, analyze, buffer);

    pthread_join(thread1, NULL);
    pthread_join(thread2, NULL);
}
return 0;
}

标签: cmultithreading

解决方案


推荐阅读