Linux 使用 FFTW库在多线程环境下的线程安全问题分析与解决方案

文章讨论了在使用FFTW库时遇到的多线程内存问题,指出fftw_execute是唯一线程安全的函数,需避免同时调用其他函数。提供两种解决方案:官方推荐使用带有线程安全的API接口并管理锁,以及从FFTW-3.3.5开始的计划器线程安全API。

FFTW库在多线程环境下的线程安全问题分析与解决方案

一、问题现象

在多线程环境下使用 FFTW 库时,程序出现以下问题:

  • 出现信号 11(SIGSEGV,段错误)
  • 出现信号 6(SIGABRT,异常终止)
  • 其他内存相关问题

二、原因分析

2.1 官方文档说明

根据 FFTW 官方文档(5.4 Thread safety):

Users writing multi-threaded programs (including OpenMP) must concern themselves with the thread safety of the libraries they use—that is, whether it is safe to call routines in parallel from multiple threads. FFTW can be used in such an environment, but some care must be taken because the planner routines share data (e.g. wisdom and trigonometric tables) between calls and plans.

The upshot is that the only thread-safe routine in FFTW is fftw_execute (and the new-array variants thereof). All other routines (e.g. the planner) should only be called from one thread at a time.

Note also that, since the plan is not modified by fftw_execute, it is safe to execute the same plan in parallel by multiple threads. However, since a given plan operates by default on a fixed array, you need to use one of the new-array execute functions so that different threads compute the transform of different data.

2.2 问题根源

  1. 共享资源冲突:

    • 规划器函数共享全局数据(wisdom 和三角函数表)
    • 多线程并发访问导致数据竞争
    • 非线程安全函数被并发调用
  2. 不可重入性:

    • fftw_execute 外的函数都不是线程安全的
    • 并发调用会导致内存破坏和未定义行为

三、解决方案

3.1 方案一:使用线程安全 API

#include <fftw3.h>

// 线程安全的执行函数
void thread_safe_fft_execute(fftw_plan plan, fftw_complex *in, fftw_complex *out) {
   
   
    // 这些变体是线程安全的
    fftw_execute_dft(plan, in, out);
}

// 对于实数变换
void thread_safe_fft_execute_r2r(fftw_plan plan, double *in, double *out) {
   
   
    fftw_execute_r2r(plan, in, out);
}

// 对于分离的复数数组
void thread_safe_fft_execute_split(fftw_plan plan, 
                                 double *ri, double *ii, 
                                 double *ro, double *io) {
   
   
    fftw_execute_split_dft(plan, ri, ii, ro, io);
}

3.2 方案二:互斥锁保护

#include <pthread.h>
#include <fftw3.h>

// 定义全局互斥锁
static pthread_mutex_t fftw_mutex = PTHREAD_MUTEX_INITIALIZER;

// 线程安全的计划创建
fftw_plan thread_safe_plan_create(int n, fftw_complex
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值