Linux内核中pthread_mutex_lock
和pthread_cond_wait
的等价物是什么。以及如何使用它们。你能否提供简单的(hello world)例子。
答案 0 :(得分:4)
答案 1 :(得分:4)
mutex_lock()
和mutex_unlock()
我们应该在使用mutex_init()
(来自#include <linux/mutex.h>
)之前启用互斥锁
pthread_cond_wait
wait_event_interruptible()
和wake_up_interruptible()
我们应该使用init_waitqueue_head()
(来自#include <linux/wait.h>
)
答案 2 :(得分:2)
我很久以前(1999-ish)为Linux内核编程创建了一个互斥和条件库,并用于各种项目。
我称之为LMC(linux互斥和条件变量)。这是在内核中存在互斥类型之前。
http://www.kylheku.com/~kaz/lmc.html
最近,我添加了一个很酷的新函数,其语义是“放弃互斥量等待条件变量,和同时轮询多个文件描述符,直到给定的超时。”< / p>
我在内核线程中使用了这个内核线程,它监视各种共享对象的更新,并且同时与内核套接字通信。
检查出来:
/**
* 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;