为了确保正确性和一致性,我们可以编写带有原子递增函数的并发安全代码。
C语言中,可以使用GCC内置函数__sync_fetch_and_add()来实现原子递增操作。示例如下:
int atomic_increment(int* variable) {
return __sync_fetch_and_add(variable, 1);
}
此函数接受一个int类型指针作为参数(表示要递增的整数变量),它会返回递增后的值。
在使用该函数的时候,为了避免竞争,需要在多线程中使用互斥锁。在以下示例中,我们使用pthread库实现了互斥锁。
#include
int counter = 0;
pthread_mutex_t lock;
void* increment(void* arg) {
for (int i=0; i<10000; i++) {
pthread_mutex_lock(&lock);
atomic_increment(&counter);
pthread_mutex_unlock(&lock);
}
return NULL;
}
int main() {
pthread_t thread1, thread2;
pthread_mutex_init(&lock, NULL);
pthread_create(&thread1, NULL, increment, NULL);
pthread_create(&thread2, NULL, increment, NULL);
pthread_join(thread1, NULL);
pthread_join(thread2, NULL);
pthread_mutex_destroy(&lock);
printf("Counter value: %d\n", counter);
return 0;
}
在上述示例中,我们创建两个线程来递增计数器。它们都使用了原子递增函数,同时也使用互斥锁来避免竞争。
最后,我们打印出计数器的值,以确保递增函数的正确性。