- 论坛徽章:
- 2
|
本帖最后由 lhd666 于 2016-11-05 11:57 编辑
我写了一段图片压缩的代码,这段代码在单线程的时候没发现异常,可一旦多线程运行,就会报段错误,接收到SIGSEGV信号。我使用gdb进行调试,每次where的时候,报错都不一样,可能是因为我不太会用gdb。只好贴上代码,希望大家帮我看看,是不是哪儿写的不对。这段代码运行的时候,依然会压缩出几张图片来。
操作系统:fedora25
gcc:6.2.1
ImageMagick:6.9.3
- #include <stdio.h>
- #include <stdlib.h>
- #include <pthread.h>
- #include <wand/magick_wand.h>
- static int image_compress(const char *infile, const char *outfile, size_t max)
- {
- MagickBooleanType status;
- MagickWand *wand;
- int width, height;
- int ret = -1;
- MagickWandGenesis();
-
- wand = NewMagickWand();
- status = MagickReadImage(wand, infile);
- if (status == MagickFalse)
- goto out;
- width = MagickGetImageWidth(wand);
- height = MagickGetImageHeight(wand);
- if (width <= max && height <= max) {
- ret = 1;
- goto out;
- }
- if (width > height) {
- height = height * max / width;
- if (height == 0)
- height = 1;
- width = max;
- } else {
- width = width * max / height;
- if (width == 0)
- width = 1;
- height = max;
- }
- MagickResetIterator(wand);
- while (MagickNextImage(wand) != MagickFalse)
- MagickResizeImage(wand, width, height, LanczosFilter, 1.0);
- status = MagickWriteImages(wand, outfile, MagickTrue);
- if (status == MagickFalse)
- goto out;
- ret = 0;
- out:
- DestroyMagickWand(wand);
- MagickWandTerminus();
- return ret;
- }
- void *thread_func(void *arg)
- {
- const char *infile = arg;
- char outfile[256];
- for (int i = 0; i < 10; i++) {
- snprintf(outfile, sizeof(outfile),
- "%ld-%d", pthread_self(), i);
- image_compress(infile, outfile, 1024);
- }
- return NULL;
- }
- #define ARRAY_LENGTH(a) (sizeof(a) / sizeof((a)[0]))
- int main(int argc, char **argv)
- {
- pthread_t tid[4];
- if (argc != 2) {
- fprintf(stderr, "Useage: %s <input image filename>\n", argv[0]);
- exit(EXIT_FAILURE);
- }
- for (int i = 0; i < ARRAY_LENGTH(tid); i++)
- pthread_create(&tid[i], NULL, thread_func, argv[1]);
- for (int i = 0; i < ARRAY_LENGTH(tid); i++)
- pthread_join(tid[i], NULL);
- return 0;
- }
复制代码
|
|