为什么 pthread_equal 是线程安全的? [英] Why is pthread_equal threadsafe?

查看:56
本文介绍了为什么 pthread_equal 是线程安全的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我看一下 pthread_equal 的实现,它看起来如下:

If I look at the implementation of pthread_equal it looks as follows:

int
__pthread_equal (pthread_t thread1, pthread_t thread2)
{
  return thread1 == thread2;
}
weak_alias (__pthread_equal, pthread_equal)

typedef unsigned long int pthread_t;

Posix 文档说 pthread_equal 是线程安全的.但是对 pthread_equals 的调用会复制并因此访问 thread1thread2 变量.如果这些变量是全局变量,并且此时被另一个线程更改,这将导致未定义的行为.

Posix documentation says pthread_equal is threadsafe. But the call to pthread_equals copies and therefore accesses the thread1 and thread2 variables. If those variables are global and changed in this moment by another thread this would lead to undefined behavior.

那么 pthread_t 不应该是原子的吗?或者它是否以原子方式运行,以其他方式确保?

So should pthread_t not be an atomic? Or does it behave atomically which is ensured in some other way?

推荐答案

pthread_equal 的这个实现(将特定于它所使用的 POSIX 实现)不访问除本地之外的任何变量那些.在 C 中,参数总是按值传递.thread1thread2 是函数中的局部变量,它们从调用者在进行调用时使用的表达式中获取它们的值.

This implementation of pthread_equal (which is going to be specific to the POSIX implementation it goes with) does not access any variables except local ones. In C, arguments are always passed by value. thread1 and thread2 are local variables in the function who take their values from the expressions the caller uses when making the call.

话虽如此,即使没有,也不会有线程不安全的问题.相反,如果调用者访问了 pthread_t 对象,而这些对象可以被其他线程同时更改,而没有使用适当的同步机制来排除这种情况,那么这是调用者中的数据竞争错误,而不是被调用者中的线程安全问题.

With that said, even if they weren't, there would be no problem of thread-unsafety here. Rather, if the caller accessed pthread_t objects that could be changed concurrently by other threads without using appropriate synchronization mechanisms to preclude that, it's a data race bug in the caller, not a thread-safety matter in the callee.

这篇关于为什么 pthread_equal 是线程安全的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆