gpt4 book ai didi

c - C 中的线程安全与原子性

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

据我所知,可以调用线程安全函数而不需要互斥锁或信号量。他们不能吗?

例如,strcpy()strdup() 是一种线程安全函数。

但是当我阅读手册页时,我看到了以下内容,并且不理解这句话以及粗体示例。

Being MT-Safe does not imply a function is atomic, nor that it uses any of the memory synchronization mechanisms POSIX exposes to users. It is even possible that calling MT-Safe functions in sequence does not yield an MT-Safe combination. For example, having a thread call two MT-Safe functions one right after the other does not guarantee behavior equivalent to atomic execution of a combination of both functions, since concurrent calls in other threads may interfere in a destructive way.

线程函数中的以下用法是否错误?如果是,错误的地方是什么?如果不是,加粗的引述是什么意思?

char *s1 = calloc(14, 1);
char *s2 = calloc(6, 1);
char *s3 = strdup("soner");
char *s4 = strdup("stackoverflow");
strcpy(s2, s3);
strcpy(s1, s4);
s1[13] = s2[5] = 0;

mutex_lock(&mtx);
printf("%s %s", s1, s2);
fflush(stdout);
mutex_unlock(&mtx);

free(s1);
free(s2);
free(s3);
free(s4);

最佳答案

在此上下文中的“MT 安全”仅意味着您可以从多个线程调用该函数,而不是线程之间有任何同步。

例如,您有两个线程,其中一个正在执行 strcpy(s1, "foo"),另一个正在执行 strcpy(s1, "bar") (并且 s1 是线程之间共享的缓冲区),那么您就会发生数据争用,因为两个线程可能会同时尝试写入目标 s1

关于c - C 中的线程安全与原子性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56150004/

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