在C语言中,要使函数成为原子操作,可以使用原子操作库,如C11标准中的stdatomic.h
。原子操作是一种不可拆分的操作,它的执行不会被其他线程或进程中断。
以下是一个使用C11原子操作库的示例:
#include <stdatomic.h>
#include<stdio.h>
#include<threads.h>
atomic_int counter = ATOMIC_VAR_INIT(0);
int increment(void *arg) {
for (int i = 0; i < 100000; i++) {
atomic_fetch_add_explicit(&counter, 1, memory_order_relaxed);
}
return 0;
}
int main(void) {
thrd_t threads[2];
thrd_create(&threads[0], increment, NULL);
thrd_create(&threads[1], increment, NULL);
thrd_join(threads[0], NULL);
thrd_join(threads[1], NULL);
printf("Counter: %d\n", atomic_load_explicit(&counter, memory_order_relaxed));
return 0;
}
在这个示例中,我们使用了atomic_fetch_add_explicit
函数来原子地增加计数器的值。memory_order_relaxed
参数表示内存顺序为relaxed,即不强制执行特定的内存顺序。
需要注意的是,原子操作并不是适用于所有场景。在某些情况下,可能需要使用互斥锁或其他同步机制来确保线程安全。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云