tqt507 pthread 多线程测试 atomic 原子操作
//
// tqt057 测试结果 find /opt -name *atomic.h* // aarch64-linux-gnu-gcc demoatomic.c -o demoatomic -pthread -I/opt/EmbedSky/TQT507/CoreA/longan/kernel/linux-4.9/tools/include // cp ./demoatomic /home/book/nfs_rootfs #include <linux/atomic.h> #include <unistd.h> #include <stdio.h> #include <pthread.h> /* 定义一个原子变量 */ static atomic_t count = ATOMIC_INIT(0); #define pthidall 20 pthread_t pthid[pthidall]; int count_total=20000; static void *pthread_test(void *arg) { for (int i = 0; i < count_total; i++) { atomic_inc(&count); } } /* 在函数中使用原子操作 */ int main(void) { int val = 0; for (int i = 0; i < pthidall; i++) { pthread_create(&pthid[i],NULL,pthread_test, NULL); } for (int i = 0; i < pthidall; i++) { if ( pthread_join ( pthid[i], NULL ) ) { printf("error join thread->%d \n",pthid[i]); } } /* 原子自增 */ //atomic_inc(&count); //atomic_set(atomic_t * v, int i); /* 读取原子变量值 */ val = atomic_read(&count); printf("pthread test atomic_inc->%d\n",val);//pthidall*count_total /* 设置原子变量值 */ atomic_set(&count, 5); val = atomic_read(&count); printf("atomic_set->%d\n",val); //生下的几个报错没有此函数 /* 原子比较并交换:如果原子变量值为 5,则将其设置为 7。 */ //val = atomic_read(&count); printf("atomic_read->%d\n",val); //atomic_cmpxchg(&count, 5, 7); //val = atomic_read(&count); printf("atomic_cmpxchg 5->7 ->%d\n",val); //val = atomic_read(&count); printf("atomic_read->%d\n",val); //atomic_cmpxchg(&count, 0, 1); //val = atomic_read(&count); printf("atomic_cmpxchg 0->1 ->%d\n",val); /* 原子自减 */ //val = atomic_read(&count); printf("atomic_read->%d\n",val); //atomic_dec(&count); //val = atomic_read(&count); printf("atomic_dec->%d\n",val); /* 原子加操作 */ //val = atomic_read(&count); printf("atomic_read->%d\n",val); //atomic_add(2, &count); //val = atomic_read(&count); printf("atomic_add->%d\n",val); /* 原子减操作 */ //val = atomic_read(&count); printf("atomic_read->%d\n",val); //atomic_sub(1, &count); //val = atomic_read(&count); printf("atomic_sub->%d\n",val); return 0; }
//