#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <stdatomic.h>
// 共享变量
int x = 1;
// 线程函数
void *thread_func(void *arg) {
int nval = *(int *)arg;
int oval = x;
while (!atomic_compare_exchange_weak(&x, &oval, nval)) {
oval = x;
}
printf("Thread %d: x = %d\n", nval, x);
return NULL;
}
int main() {
pthread_t t1, t2;
int nval1 = 2, nval2 = 3;
pthread_create(&t1, NULL, thread_func, &nval1);
pthread_create(&t2, NULL, thread_func, &nval2);
pthread_join(t1, NULL);
pthread_join(t2, NULL);
return 0;
}
在这个例子中,我们定义了一个共享变量x,并创建了两个线程t1和t2,分别想要将x的值改为2和3。在线程函数thread_func中,我们使用atomic_compare_exchange_weak函数来原子地比较和交换x的值。具体来说,我们首先将x的值存储到oval中,然后使用atomic_compare_exchange_weak函数来比较oval和x的值。如果它们相等,则将nval的值存储到x所指向的位置,并返回true。如果它们不相等,则将x的值存储到oval中,并返回false。如果返回false,则说明在比较和交换的过程中,x的值已经被其他线程修改了,因此我们需要重新读取x的值,并再次进行比较和交换,直到成功为止。最后,我们在线程函数中打印出x的值,以便观察结果。