锁机制
不可睡眠锁
自旋锁示例代码
kthread.h
kthread_run()
#define kthread_create(threadfn, data, namefmt, arg...) \
kthread_create_on_node(threadfn, data, -1, namefmt, ##arg)
struct task_struct *kthread_create_on_cpu(int (*threadfn)(void *data),
void *data,
unsigned int cpu,
const char *namefmt);
/**
* kthread_run - create and wake a thread.
* @threadfn: the function to run until signal_pending(current).
* @data: data ptr for @threadfn.
* @namefmt: printf-style name for the thread.
*
* Description: Convenient wrapper for kthread_create() followed by
* wake_up_process(). Returns the kthread or ERR_PTR(-ENOMEM).
*/
#define kthread_run(threadfn, data, namefmt, ...) \
({ \
struct task_struct *__k \
= kthread_create(threadfn, data, namefmt, ## __VA_ARGS__); \
if (!IS_ERR(__k)) \
wake_up_process(__k); \
__k; \
})
=================
#include <linux/module.h>
#include <linux/kthread.h>
#define MAX_KTHREAD 10
static struct task_struct *threads[MAX_KTHREAD];
static int thread_do(void *data)
{
printk("run ...\n");
}
static int create_thread(void)
{
int i;
for(i=0;i<MAX_KTHREAD;i++){
struct task_struct *thread;
thread=kthread_run(thread_do,NULL,"thread-%d",i);
if(IS_ERR(thread))
return -1;
threads[i]=thread;
}
return 0;
}
================
退出时候的处理,清理一些资源
static void cleanup_threads(void)
{
int i;
for(i=0;i<MAX_KTHREAD;i++)
{
if(threads[i]){
kthread_stop(threads[i]);
}
}
}
static __init int minit(void)
{
// printk("testpar= %#x.\n",testpar);
printk("call %s.\n",__FUNCTION__);
// other_function();
if(create_threads())
{
cleanup_threads();
return -1;
}
return 0;
}
============
产生了竞争条件
#define MAX_KTHREAD 10
static struct task_struct *threads[MAX_KTHREAD];
static int thread_do(void *data)
{
printk("run ...\n");
while(!kthread_should_stop())
{
msleep(10);
}
return 0;
}
apuser@jianzhangubtnb:~/mymodule/m1$ sudo dmesg
apuser@jianzhangubtnb:~/mymodule/m1$ sudo rmmod tmain
ERROR: Module tmain does not exist in /proc/modules
apuser@jianzhangubtnb:~/mymodule/m1$ sudo insmod tmain.ko
apuser@jianzhangubtnb:~/mymodule/m1$ sudo dmesg
[ 6483.928804] call minit.
[ 6483.928871] run ...
[ 6483.929245] run ...
[ 6483.929294] run ...
[ 6483.929318] run ...
[ 6483.929337] run ...
[ 6483.929356] run ...
[ 6483.929376] run ...
[ 6483.929675] run ...
[ 6483.929693] run ...
[ 6483.929708] run ...
apuser@jianzhangubtnb:~/mymodule/m1$ ps aux |grep thread
root 2 0.0 0.0 0 0 ? S Mar15 0:00 [kthreadd]
root 7816 0.1 0.0 0 0 ? D 00:31 0:00 [thread-0]
root 7817 0.1 0.0 0 0 ? D 00:31 0:00 [thread-1]
root 7818 0.1 0.0 0 0 ? D 00:31 0:00 [thread-2]
root 7819 0.1 0.0 0 0 ? D 00:31 0:00 [thread-3]
root 7820 0.1 0.0 0 0 ? D 00:31 0:00 [thread-4]
root 7821 0.1 0.0 0 0 ? D 00:31 0:00 [thread-5]
root 7822 0.1 0.0 0 0 ? D 00:31 0:00 [thread-6]
root 7823 0.1 0.0 0 0 ? D 00:31 0:00 [thread-7]
root 7824 0.1 0.0 0 0 ? D 00:31 0:00 [thread-8]
root 7825 0.1 0.0 0 0 ? D 00:31 0:00 [thread-9]
apuser 7829 0.0 0.0 13592 940 pts/0 R+ 00:33 0:00 grep --color=auto thread