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 问题根源
-
共享资源冲突:
- 规划器函数共享全局数据(wisdom 和三角函数表)
- 多线程并发访问导致数据竞争
- 非线程安全函数被并发调用
-
不可重入性:
- 除
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

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

被折叠的 条评论
为什么被折叠?



