OS版本:openEuler 22.03 LTS
架构:x86_64
描述:测试下linux内核驱动常用的几个atomic操作函数。
创建两个内核线程thread_inc和thread_dec,分别调用atomic_inc和atomic_dec函数,atomic_inc每隔1秒调用一次,atomic_dec每隔2秒调用一次,调用完成之后使用atomic_read接口打印atomic值。
代码如下:
// atomic_test.c
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/sizes.h>
#include <linux/delay.h>
#include <linux/kthread.h>
#include <linux/atomic.h>
static atomic_t A;
static struct task_struct *task_inc = NULL;
static struct task_struct *task_dec = NULL;
static int thread_inc(void * data)
{
while(!kthread_should_stop()) { // 判读内核线程是否应该停止
msleep(1000);
atomic_inc(&A);
printk(KERN_INFO "thread_inc is running, now atomic value A is: %d\n",
atomic_read(&A));
}
return 0;
}
static int thread_dec(void *data)
{
while (!kthread_should_stop()) {
msleep(2000);
atomic_dec(&A);
printk(KERN_INFO "thread_dec is running, now atomic value A is: %d\n",
atomic_read(&A));
}
return 0;
}
static int __init atomic_test_init(void)
{
atomic_set(&A, 0);
// 创建一个内核线程
task_inc = kthread_create(thread_inc, NULL, "kthread-inc");
if (!IS_ERR(task_inc)) {
printk(KERN_INFO "create thread success\n");
wake_up_process(task_inc); // 启动内核线程
}
task_dec = kthread_create(thread_dec, NULL, "kthread-dec");
if (!IS_ERR(task_dec)) {
printk(KERN_INFO "create thread-dec success\n");
wake_up_process(task_dec);
}
return 0;
}
static void __exit atomic_test_exit(void)
{
kthread_stop(task_dec); // 停止内核线程
kthread_stop(task_inc);
printk(KERN_INFO "atomic_test is stop!\n");
return;
}
module_init(atomic_test_init);
module_exit(atomic_test_exit);
MODULE_LICENSE("GPL");
Makefile:
obj-m+=atomic_test.o
CONFIG_MODULE_SIG=n
all:
make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) modules
clean:
make -C /lib/modules/$(shell uname -r)/build/ M=$(PWD) clean
输出结果