gpt4 book ai didi

c - 带有互斥量和信号量的 volatile 关键字

转载 作者:太空宇宙 更新时间:2023-11-04 01:20:15 26 4
gpt4 key购买 nike

问题很简单。 用于多线程的变量是否/应该是 volatile 甚至在 C 的关键部分(即互斥锁、信号量)访问?为什么/为什么不?

#include <pthread.h>

volatile int account_balance;
pthread_mutex_t flag = PTHREAD_MUTEX_INITIALIZER;

void debit(int amount) {
pthread_mutex_lock(&flag);
account_balance -= amount;//Inside critical section
pthread_mutex_unlock(&flag);
}

信号量的示例或等效思考如何?

最佳答案

Does/Should a variable used with multi-threads be volatile even accessed in critical section(i.e. mutex, semaphore) in C? Why / Why not?

没有。

volatile 在逻辑上与并发无关,因为它足够。

实际上,这不是真的 - volatile 并非无关紧要,因为它可以隐藏代码中的并发问题,因此它“大部分时间”都有效。

volatile 所做的只是告诉编译器“这个变量可以在当前执行线程之外改变”。 Volatile 绝不会强制执行任何顺序、原子性或(关键的)可见性。仅仅因为 CPU A 上的线程 2 更改了 int x,这并不意味着 CPU D 上的线程 1 甚至可以在任何特定时间看到更改 - 它有自己的缓存值和 volatile 几乎没有内存一致性方面的意义,因为它不保证顺序。

Intel文章Volatile底部最后评论:Almost Useless for Multi-Threaded Programming说得最好:

If you are simply adding 'volatile' to variables that are shared between threads thinking that fixes your shared-data problem without bothering to understand why it may not, you will eventually reap the reward you deserve.

是的,无锁代码可以使用volatile。此类代码的编写者可能会编写有关 volatile 的使用、多线程代码和其他有关编译器的极其详细的主题的教程。

关于c - 带有互斥量和信号量的 volatile 关键字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45663059/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com