gpt4 book ai didi

c - 在多线程共享进程中,原子操作似乎比信号量操作慢

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

尽管指令数量有所减少,但您能想到原子操作看起来比信号量慢的任何充分理由吗?

示例代码:

 void increment(){
if (strcmp(type, "ATOMIC") == 0) {
for (int i = 0; i < RUN_TIME; ++i) {
atomic_fetch_add_explicit(&count, 1, memory_order_relaxed);
}
}
if (strcmp(type, "SEMAPHORE") == 0){
for (int i = 0; i < RUN_TIME; ++i) {
sem_wait(sem);
count++;
sem_post(sem);
}
}
}

输出:

   time ./CMAIN "SEMAPHORE";time ./CMAIN "ATOMIC";
[C] SEMAPHORE, count 4000000

real 0m0.039s
user 0m0.029s
sys 0m0.002s
[C] ATOMIC, count 4000000

real 0m0.092s
user 0m0.236s
sys 0m0.003s

最佳答案

无法重现。对于 10^9 次迭代,我得到(来自 bash、i5、x86_64、Linux):

$ TIMEFORMAT="%RR %UU %SS"
$ gcc atomic.c -Os -lpthread && ( time ./a.out ATOMIC ; time ./a.out SEMAPHORE )
1.572R 1.568U 0.000S #ATOMIC
5.542R 5.536U 0.000S #SEMAPHORE

(大约 4000000 次迭代的相同比率。)

我的 atomic.c(你的例子填满了空白):

#include <stdio.h>
#include <string.h>
#include <stdatomic.h>
#include <semaphore.h>
#define RUN_TIME 100000000
char * type;
sem_t *sem;

_Atomic int count = ATOMIC_VAR_INIT(0);

void increment(){
if (strcmp(type, "ATOMIC") == 0) {
for (int i = 0; i < RUN_TIME; ++i) {
atomic_fetch_add_explicit(&count, 1, memory_order_relaxed);
}
}
if (strcmp(type, "SEMAPHORE") == 0){
for (int i = 0; i < RUN_TIME; ++i) {
sem_wait(sem);
count++;
sem_post(sem);
}
}
}

int main(int C, char**V)
{
sem_t s;
sem_init(&s, 0, 1);
sem = &s;
type = V[1];
increment();
}

请发布mcve ,以及您的平台规范。

关于c - 在多线程共享进程中,原子操作似乎比信号量操作慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47225518/

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