在 ARM64 架构中,数据加载和存储是基于寄存器的,因此在多线程环境中,当一个线程正在读取(加载)或写入(存储)一个数据时,另一个线程可能会同时进行相同的操作,造成数据竞争问题。
为避免 ARM64 64 位数据加载/存储竞争问题,可采用以下方法:
示例代码:
// 互斥锁
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; int data = 0;
void* thread_func(void* arg){ int i; for(i = 0; i < 1000000; i++){ pthread_mutex_lock(&mutex); data++; pthread_mutex_unlock(&mutex); } return NULL; }
int main(){ pthread_t tid1, tid2; pthread_create(&tid1, NULL, thread_func, NULL); pthread_create(&tid2, NULL, thread_func, NULL); pthread_join(tid1, NULL); pthread_join(tid2, NULL); printf("data=%d\n", data); return 0; }
// 读写锁
pthread_rwlock_t rwlock = PTHREAD_RWLOCK_INITIALIZER; int data = 0;
void* read_thread(void* arg) { int i; for(i = 0; i < 1000000; i++){ pthread_rwlock_rdlock(&rwlock); printf("read_thread: data=%d\n", data); pthread_rwlock_unlock(&rwlock); } return NULL; }
void* write_thread(void* arg) { int i; for(i = 0; i < 1000000; i++){ pthread_rwlock_wrlock(&rwlock); data++; pthread_rwlock_unlock(&rwlock); } return NULL; }
int main() { pthread_t tid1, tid2; pthread_create(&tid1, NULL, read_thread, NULL);