Linux内核中与pthread_mutex_lock和pthread_cond_wait等效的函数是什么?

3

pthread_mutex_lockpthread_cond_wait在Linux内核中的等效操作是什么,如何使用它们?能否提供简单的(hello world)示例。

3个回答

4
  • 对于互斥量(正如Als所说):

使用mutex_lock()mutex_unlock(),在使用之前应使用mutex_init()初始化互斥量(来自#include <linux/mutex.h>

  • 对于pthread_cond_wait的等效操作

使用wait_event_interruptible()wake_up_interruptible(),在使用之前应使用init_waitqueue_head()初始化wait_queue_head(来自#include <linux/wait.h>


3

在内核空间中不能使用任何库调用,因为内核模块直接链接到内核。

你可以使用:

mutex_lock()mutex_unlock()

它们是通过linux/mutex.h提供的。


1
如何从其他模块创建内核模块等待条件。我正在寻找与pthread_cond_wait相当的等效物。 - MOHAMED
3
您需要类似于等待队列这样的东西来实现。 - Alok Save

2
我很久以前(大约1999年)为Linux内核编程制作了一个互斥锁和条件库,并在之后的各种项目中使用它。我称其为LMC(linux mutexes and condition variables),当时内核中还没有互斥锁类型。
最近,我添加了一个很酷的新功能,其语义是“放弃互斥锁以等待条件变量,并同时轮询多个文件描述符,直到给定超时时间”。
我在内核线程中使用它来监视各种共享对象的更新,并与内核套接字同时通信。
看看这个:http://www.kylheku.com/~kaz/lmc.html
/**
 * Atomically give up the mutex and wait on the condition variable.
 * Wake up if the specified timeout elapses, or if a signal is delivered.
 * Additionally, also wait on the specified file descriptors to become
 * ready, combining condition waiting with poll().
 * KCOND_WAIT_SUCCESS means the condition was signaled, or one or more
 * file descriptors are ready.
 * Also, a negative value can be returned indicating an error!
 * (The poll needs to dynamically allocate some memory for the wait table).
 * The timeout is relative to the current time, specifying how long to sleep in
 * jiffies (CPU clock ticks).
 */
int kcond_timed_wait_rel_poll(kcond_t *, kmutex_t *, long, 
                              kcond_poll_t *, unsigned int);

kcond_poll_t结构体数组是需要您自己创建和填充的,该结构体如下所示。它有一个类型字段,因此您可以等待套接字(struct socket *)或文件(struct file *):

/**
 * Structure for file-descriptor polling condition waits.
 * This resembles struct pollfd, but uses a direct file descriptor
 * pointer rather than a file descriptor number.  Also,
 * it contains the wait queue by which the process is enqueued
 * to wait on that descriptor. Thus our poll function doesn't
 * have to dynamically allocate wait queue tables. It gets
 * them from this array! (But this means that the array cannot
 * be used by multiple threads at the same time to do polling!)
 */
typedef struct {
        kcond_poll_type_t type;  /* Must set this. */
        union {                 /* Must set union field according to type. */
                struct file *file;      
                struct socket *sock;
        } obj;
        short events;           /* And this. */
        short revents;          /* Check response in this. */
        wait_queue_t wait;          /* Internal, don't set. */
        wait_queue_head_t *queue;   /* Internal, don't set */
} kcond_poll_t;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接