当前位置: C语言 -- 标准库 -- <stdatomic.h> -- atomic_signal_fence

atomic_signal_fence函数


概要:
#include <stdatomic.h>
void atomic_signal_fence(memory_order order);

描述:

该函数等价于atomic_thread_fence函数,区别在于该函数建立的排序约束仅限于线程和同一线程中执行的信号处理函数之间。

该函数可用于指定线程中执行的操作对信号处理函数可见的顺序。编译器的优化、加载操作和存储操作的重排与atomic_thread_fence函数相同,但不会发出atomic_thread_fence将插入的硬件栅栏指令。


参数:
memory_order order

枚举常量,显式地指定内存顺序。


返回值:

无。


范例:
1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
/*函数atomic_signal_fence范例*/

#ifdef __STDC_NO_ATOMICS__
#error "Implementation does not support atomic types."
#endif

#ifdef __STDC_NO_THREADS__
#error "Implementation does not support multi-threads."
#endif

#include <signal.h>
#include <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>

atomic_int aNumber = 0;
int number;

/*信号处理函数。*/
void sigfpeHandler(int sig)
{
    /*其它代码。*/
    while(!atomic_load_explicit(&aNumber, memory_order_relaxed))
        ;
    atomic_signal_fence(memory_order_acquire);
    puts("Floating-point exception.");
    /*其它代码。*/
}

/*新线程中执行的函数。*/
int func(void *arg)
{
    /*设置信号处理函数。*/
    if(signal(SIGFPE, sigfpeHandler) == SIG_ERR)
    {
        perror("Failed to install SIGFPE handler.");
        exit(EXIT_FAILURE);
    }

    printf("Input the value of number: ");
    scanf("%d", &number);
    
    atomic_signal_fence(memory_order_release);
    atomic_store_explicit(&aNumber, 1, memory_order_relaxed);

    if(number)
    {
        /*执行其它运算,例如:10/number。*/
    }
    else
    {
        raise(SIGFPE);
    }
    
    thrd_exit(0);
}

int main(void)
{
    thrd_t threadId;

    if(thrd_create(&threadId, func, NULL) != thrd_success)
    {
        fputs("Fail to create thread.", stderr);
        exit(EXIT_FAILURE);
    }
    
    thrd_join(threadId, NULL);
    
    return 0;
}


结果:

假设输入是0,将输出:

Input the value of number: 0

Floating-point exception.

注:使用Pelles C编译。


相关内容:
atomic_thread_fence 原子线程栅栏函数。