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

kill_dependency宏


概要:
#include <stdatomic.h>
type kill_dependency(type y);

描述:

该宏是函数式宏,用以终止依赖关系链,参数y不携带对返回值的依赖关系,即memory_order_consume原子加载操作启动的依赖关系链不会超出宏kill_dependency的返回值。


参数:
type y

表达式,其返回值将从依赖关系链中删除。


返回值:

该宏返回参数y的值。


范例:
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 
/*宏kill_dependency范例*/

#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 <stdatomic.h>
#include <stdio.h>
#include <stdlib.h>
#include <threads.h>

#define THREADS 2

atomic_int aNumber = 0;
const int data[5] = {1,2,3,4,5};

/*线程一中执行的函数。*/
int funcOne(void *arg)
{
    /*其它操作。*/

    atomic_store_explicit(&aNumber, 1, memory_order_release);

    /*其它操作*/

    thrd_exit(0);
}

/*线程二中执行的函数。*/
int funcTwo(void *arg)
{
    int i;
    while(!(i = atomic_load_explicit(&aNumber, memory_order_consume)))
        ;
        
    /*其它操作。*/
    
    int index = kill_dependency(i);     //终止依赖关系。
    
    /*其它操作,例如:使用data[index]。*/

    thrd_exit(0);
}

int main(void)
{
    thrd_t threadId[THREADS];

    if(thrd_create(&threadId[0], funcOne, NULL) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    }
    
    if(thrd_create(&threadId[1], funcTwo, NULL) != thrd_success)
    {
        perror("thrd_create error");
        exit(EXIT_FAILURE);
    } 

    thrd_join(threadId[0], NULL);
    thrd_join(threadId[1], NULL);

    return 0;
}


结果:

过多的使用依赖关系会降低程序性能;有些情况下可以使用kill_dependency宏来终止一些不必要的依赖关系。在本例中,数组data是个全局只读数组,通过atomic_load_explicit(&aNumber, memory_order_consume)获取数组下标后,如果不需要再修改数组下标,可以使用kill_dependency宏来通知编译器不需要重新读取数组下标。

注:使用Pelles C编译。


相关内容:
memory_order 表示内存顺序的类型。
memory_order_consume 表示内存顺序的枚举常量。