wait_for_completion_interruptible_timeout
是 Linux 内核中用于等待 completion 事件的一个函数,它结合了等待 completion 的功能、可中断性(即如果线程在等待过程中接收到信号,它会提前返回)以及超时机制。
函数的原型如下:
c复制代码
long wait_for_completion_interruptible_timeout(struct completion *comp, unsigned long timeout); |
comp
:指向要等待的 completion 结构的指针。timeout
:超时时间(以 jiffies 为单位,通常是内核用于计时的一种单位)。
返回值:
- 如果 completion 在超时之前发生,返回剩余的 jiffies(从超时时间中减去等待所消耗的时间)。
- 如果在等待过程中线程被信号中断,返回
-ERESTARTSYS
。 - 如果超时时间到达而 completion 还未发生,返回
0
。
使用说明:
-
初始化一个 completion 变量,通常使用
DECLARE_COMPLETION
宏声明并在需要时调用init_completion
函数进行初始化。 -
在需要等待 completion 的线程中,调用
wait_for_completion_interruptible_timeout
函数,并传入相应的 completion 变量和超时时间。 -
在另一个线程中,当某个任务完成时,调用
complete
或complete_all
函数来标记 completion。
示例:
c复制代码
#include <linux/completion.h> | |
#include <linux/interrupt.h> | |
DECLARE_COMPLETION(my_comp); | |
void worker_thread(void *arg) { | |
// 执行一些工作... | |
// 当工作完成时,标记completion | |
complete(&my_comp); | |
} | |
int main_thread(void) { | |
unsigned long timeout = jiffies + msecs_to_jiffies(5000); // 设置5秒超时 | |
int ret; | |
// 初始化completion | |
init_completion(&my_comp); | |
// 创建工作线程(此处省略线程创建代码) | |
// ... | |
// 等待completion完成,可中断且带超时 | |
ret = wait_for_completion_interruptible_timeout(&my_comp, timeout); | |
if (ret == 0) { | |
// 超时发生,处理超时情况 | |
} else if (ret < 0) { | |
// 等待过程中被信号中断 | |
if (signal_pending(current)) { | |
// 处理接收到的信号 | |
} | |
} else { | |
// completion 在超时前发生 | |
} | |
// 继续执行后续操作... | |
} |
在上面的示例中,main_thread
等待 worker_thread
完成工作并标记 completion。如果等待时间超过5秒,或者等待过程中 main_thread
接收到信号,wait_for_completion_interruptible_timeout
将返回,然后可以根据返回值判断是超时还是被信号中断。