如果我有以下的 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 上使用 GCC 8.3.0 和 -std=c99 编译选项,将上述“程序”扩展到1000个线程,重复运行100000次,并且看起来它们不会互相干扰;
然而,我认为这样的实验并不足以得出在所有平台上都是线程安全的结论。
编辑1:
这个问题是关于在不同的线程中访问不同的元素,而不是在不同的线程中访问同一个元素;也就是说,
例如线程 1
读取/写入 arr[1]
,而线程 2
读取/写入 arr[2]
。