访问 C 数组线程中的不同元素是否安全?
Is access to different elements in a C array thread safe?
假设我有以下 C 代码:
int my_global_arr[100];
或更一般地说,
some_type *my_global_arr = malloc(some_size * sizeof(some_type);
在多个线程中同时访问(读写)不同 元素是否安全?
例如,如果我有
void *my_thread(void *index){
int idx = *((int *)(index));
my_global_arr[idx] = idx;
return NULL;
}
并且在main()
int a = 1;
int b = 2;
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, my_thread, &a);
pthread_create(&thread2, NULL, my_thread, &b);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
能保证两个线程不会互相干扰吗?
我的实验:
我尝试 运行 上面的“程序”,在 x86_64 CPU 上扩展到 1000 个线程,100000 次
使用 GCC 8.3.0,-std=c99,看起来它们不会相互干扰;
但是,我认为这样的实验还不足以得出这样的访问权限是
在所有平台上都是线程安全的。
编辑 1:
这个问题是关于在不同的环境中访问 different 元素
线程,不同线程中的同一个元素;那是,
例如,thread-1
reads/writes 到 arr[1]
而 thread-2
reads/writes 到 arr[2]
.
[已编辑]
在 C 中访问数组的不同元素是完全线程安全的。
访问不同的元素总是 100% 安全的。
如果能保证在同一时刻,每个元素只被一个线程访问,就是线程安全的。因为数组的每个元素(物理上)彼此不同,这意味着它们是独立的内存部分。
假设我有以下 C 代码:
int my_global_arr[100];
或更一般地说,
some_type *my_global_arr = malloc(some_size * sizeof(some_type);
在多个线程中同时访问(读写)不同 元素是否安全?
例如,如果我有
void *my_thread(void *index){
int idx = *((int *)(index));
my_global_arr[idx] = idx;
return NULL;
}
并且在main()
int a = 1;
int b = 2;
pthread_t thread1, thread2;
pthread_create(&thread1, NULL, my_thread, &a);
pthread_create(&thread2, NULL, my_thread, &b);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
能保证两个线程不会互相干扰吗?
我的实验:
我尝试 运行 上面的“程序”,在 x86_64 CPU 上扩展到 1000 个线程,100000 次
使用 GCC 8.3.0,-std=c99,看起来它们不会相互干扰;
但是,我认为这样的实验还不足以得出这样的访问权限是
在所有平台上都是线程安全的。
编辑 1:
这个问题是关于在不同的环境中访问 different 元素
线程,不同线程中的同一个元素;那是,
例如,thread-1
reads/writes 到 arr[1]
而 thread-2
reads/writes 到 arr[2]
.
[已编辑]
在 C 中访问数组的不同元素是完全线程安全的。
访问不同的元素总是 100% 安全的。
如果能保证在同一时刻,每个元素只被一个线程访问,就是线程安全的。因为数组的每个元素(物理上)彼此不同,这意味着它们是独立的内存部分。