- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
我正在寻找使用 pthread 同步语义的 C 语言中线程安全阻塞队列(多生产者/消费者)的推荐实现。
最佳答案
这是我用的
线程队列.h
#ifndef _THREADQUEUE_H_
#define _THREADQUEUE_H_ 1
#include <pthread.h>
#ifdef __cplusplus
extern "C" {
#endif
/**
* @defgroup ThreadQueue ThreadQueue
*
* Little API for waitable queues, typically used for passing messages
* between threads.
*
*/
/**
* @mainpage
*/
/**
* A thread message.
*
* @ingroup ThreadQueue
*
* This is used for passing to #thread_queue_get for retreive messages.
* the date is stored in the data member, the message type in the #msgtype.
*
* Typical:
* @code
* struct threadmsg;
* struct myfoo *foo;
* while(1)
* ret = thread_queue_get(&queue,NULL,&message);
* ..
* foo = msg.data;
* switch(msg.msgtype){
* ...
* }
* }
* @endcode
*
*/
struct threadmsg{
/**
* Holds the data.
*/
void *data;
/**
* Holds the messagetype
*/
long msgtype;
/**
* Holds the current queue lenght. Might not be meaningful if there's several readers
*/
long qlength;
};
/**
* A TthreadQueue
*
* @ingroup ThreadQueue
*
* You should threat this struct as opaque, never ever set/get any
* of the variables. You have been warned.
*/
struct threadqueue {
/**
* Length of the queue, never set this, never read this.
* Use #threadqueue_length to read it.
*/
long length;
/**
* Mutex for the queue, never touch.
*/
pthread_mutex_t mutex;
/**
* Condition variable for the queue, never touch.
*/
pthread_cond_t cond;
/**
* Internal pointers for the queue, never touch.
*/
struct msglist *first,*last;
/**
* Internal cache of msglists
*/
struct msglist *msgpool;
/**
* No. of elements in the msgpool
*/
long msgpool_length;
};
/**
* Initializes a queue.
*
* @ingroup ThreadQueue
*
* thread_queue_init initializes a new threadqueue. A new queue must always
* be initialized before it is used.
*
* @param queue Pointer to the queue that should be initialized
* @return 0 on success see pthread_mutex_init
*/
int thread_queue_init(struct threadqueue *queue);
/**
* Adds a message to a queue
*
* @ingroup ThreadQueue
*
* thread_queue_add adds a "message" to the specified queue, a message
* is just a pointer to a anything of the users choice. Nothing is copied
* so the user must keep track on (de)allocation of the data.
* A message type is also specified, it is not used for anything else than
* given back when a message is retreived from the queue.
*
* @param queue Pointer to the queue on where the message should be added.
* @param data the "message".
* @param msgtype a long specifying the message type, choice of the user.
* @return 0 on succes ENOMEM if out of memory EINVAL if queue is NULL
*/
int thread_queue_add(struct threadqueue *queue, void *data, long msgtype);
/**
* Gets a message from a queue
*
* @ingroup ThreadQueue
*
* thread_queue_get gets a message from the specified queue, it will block
* the caling thread untill a message arrives, or the (optional) timeout occurs.
* If timeout is NULL, there will be no timeout, and thread_queue_get will wait
* untill a message arrives.
*
* struct timespec is defined as:
* @code
* struct timespec {
* long tv_sec; // seconds
* long tv_nsec; // nanoseconds
* };
* @endcode
*
* @param queue Pointer to the queue to wait on for a message.
* @param timeout timeout on how long to wait on a message
* @param msg pointer that is filled in with mesagetype and data
*
* @return 0 on success EINVAL if queue is NULL ETIMEDOUT if timeout occurs
*/
int thread_queue_get(struct threadqueue *queue, const struct timespec *timeout, struct threadmsg *msg);
/**
* Gets the length of a queue
*
* @ingroup ThreadQueue
*
* threadqueue_length returns the number of messages waiting in the queue
*
* @param queue Pointer to the queue for which to get the length
* @return the length(number of pending messages) in the queue
*/
long thread_queue_length( struct threadqueue *queue );
/**
* @ingroup ThreadQueue
* Cleans up the queue.
*
* threadqueue_cleanup cleans up and destroys the queue.
* This will remove all messages from a queue, and reset it. If
* freedata is != 0 free(3) will be called on all pending messages in the queue
* You cannot call this if there are someone currently adding or getting messages
* from the queue.
* After a queue have been cleaned, it cannot be used again untill #thread_queue_init
* has been called on the queue.
*
* @param queue Pointer to the queue that should be cleaned
* @param freedata set to nonzero if free(3) should be called on remaining
* messages
* @return 0 on success EINVAL if queue is NULL EBUSY if someone is holding any locks on the queue
*/
int thread_queue_cleanup(struct threadqueue *queue, int freedata);
#ifdef __cplusplus
}
#endif
#endif
线程队列.c
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pthread.h>
#include <sys/time.h>
#include "../h/threadqueue.h"
#define MSGPOOL_SIZE 256
struct msglist {
struct threadmsg msg;
struct msglist *next;
};
static inline struct msglist *get_msglist(struct threadqueue *queue)
{
struct msglist *tmp;
if(queue->msgpool != NULL) {
tmp = queue->msgpool;
queue->msgpool = tmp->next;
queue->msgpool_length--;
} else {
tmp = malloc(sizeof *tmp);
}
return tmp;
}
static inline void release_msglist(struct threadqueue *queue,struct msglist *node)
{
if(queue->msgpool_length > ( queue->length/8 + MSGPOOL_SIZE)) {
free(node);
} else {
node->msg.data = NULL;
node->msg.msgtype = 0;
node->next = queue->msgpool;
queue->msgpool = node;
queue->msgpool_length++;
}
if(queue->msgpool_length > (queue->length/4 + MSGPOOL_SIZE*10)) {
struct msglist *tmp = queue->msgpool;
queue->msgpool = tmp->next;
free(tmp);
queue->msgpool_length--;
}
}
int thread_queue_init(struct threadqueue *queue)
{
int ret = 0;
if (queue == NULL) {
return EINVAL;
}
memset(queue, 0, sizeof(struct threadqueue));
ret = pthread_cond_init(&queue->cond, NULL);
if (ret != 0) {
return ret;
}
ret = pthread_mutex_init(&queue->mutex, NULL);
if (ret != 0) {
pthread_cond_destroy(&queue->cond);
return ret;
}
return 0;
}
int thread_queue_add(struct threadqueue *queue, void *data, long msgtype)
{
struct msglist *newmsg;
pthread_mutex_lock(&queue->mutex);
newmsg = get_msglist(queue);
if (newmsg == NULL) {
pthread_mutex_unlock(&queue->mutex);
return ENOMEM;
}
newmsg->msg.data = data;
newmsg->msg.msgtype = msgtype;
newmsg->next = NULL;
if (queue->last == NULL) {
queue->last = newmsg;
queue->first = newmsg;
} else {
queue->last->next = newmsg;
queue->last = newmsg;
}
if(queue->length == 0)
pthread_cond_broadcast(&queue->cond);
queue->length++;
pthread_mutex_unlock(&queue->mutex);
return 0;
}
int thread_queue_get(struct threadqueue *queue, const struct timespec *timeout, struct threadmsg *msg)
{
struct msglist *firstrec;
int ret = 0;
struct timespec abstimeout;
if (queue == NULL || msg == NULL) {
return EINVAL;
}
if (timeout) {
struct timeval now;
gettimeofday(&now, NULL);
abstimeout.tv_sec = now.tv_sec + timeout->tv_sec;
abstimeout.tv_nsec = (now.tv_usec * 1000) + timeout->tv_nsec;
if (abstimeout.tv_nsec >= 1000000000) {
abstimeout.tv_sec++;
abstimeout.tv_nsec -= 1000000000;
}
}
pthread_mutex_lock(&queue->mutex);
/* Will wait until awakened by a signal or broadcast */
while (queue->first == NULL && ret != ETIMEDOUT) { //Need to loop to handle spurious wakeups
if (timeout) {
ret = pthread_cond_timedwait(&queue->cond, &queue->mutex, &abstimeout);
} else {
pthread_cond_wait(&queue->cond, &queue->mutex);
}
}
if (ret == ETIMEDOUT) {
pthread_mutex_unlock(&queue->mutex);
return ret;
}
firstrec = queue->first;
queue->first = queue->first->next;
queue->length--;
if (queue->first == NULL) {
queue->last = NULL; // we know this since we hold the lock
queue->length = 0;
}
msg->data = firstrec->msg.data;
msg->msgtype = firstrec->msg.msgtype;
msg->qlength = queue->length;
release_msglist(queue,firstrec);
pthread_mutex_unlock(&queue->mutex);
return 0;
}
//maybe caller should supply a callback for cleaning the elements ?
int thread_queue_cleanup(struct threadqueue *queue, int freedata)
{
struct msglist *rec;
struct msglist *next;
struct msglist *recs[2];
int ret,i;
if (queue == NULL) {
return EINVAL;
}
pthread_mutex_lock(&queue->mutex);
recs[0] = queue->first;
recs[1] = queue->msgpool;
for(i = 0; i < 2 ; i++) {
rec = recs[i];
while (rec) {
next = rec->next;
if (freedata) {
free(rec->msg.data);
}
free(rec);
rec = next;
}
}
pthread_mutex_unlock(&queue->mutex);
ret = pthread_mutex_destroy(&queue->mutex);
pthread_cond_destroy(&queue->cond);
return ret;
}
long thread_queue_length(struct threadqueue *queue)
{
long counter;
// get the length properly
pthread_mutex_lock(&queue->mutex);
counter = queue->length;
pthread_mutex_unlock(&queue->mutex);
return counter;
}
关于c - pthread 同步阻塞队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4577961/
我正在将一些 pthreads 代码添加到我使用 autotools 构建的 Linux 应用程序中。我收到关于未在 libpthreads 中链接的错误。所以我想在 autotools 中指定 pt
libpthread 库位于 Linux 系统的哪个目录中? 最佳答案 有多种方法可以找出这一点。 只需输入 find / -name 'libpthread.so' -print找到名为 libpt
pthread 属性对象是否需要在使用它们的对象的生命周期内存在,或者在使用它们后立即销毁它们是否安全?例如: // Create the mutex attributes. pthread_mute
到目前为止我读过的所有文档似乎都表明我的 vxWorks (6.8) 版本中存在 posix 线程支持,但是一个简单的测试应用程序无法按预期执行。来源如下: tTest.h #include cla
我试图找到指定 pthreads 标准的文档。我见过各种指向 IEEE 1003.1c-1995 的链接(即 Wikipedia 或 OpenGroup )。然而,当我在 IEEE 标准站点上搜索此文
我试图找到指定 pthreads 标准的文档。我见过各种指向 IEEE 1003.1c-1995 的链接(即 Wikipedia 或 OpenGroup )。然而,当我在 IEEE 标准站点上搜索此文
我在 MSVC 2010 上运行一个 pthread,我已经包含 pthreadVC2 .lib & .dll。来自以下网站 http://sourceware.org/pthreads-win32/
我的问题是: 如何在不更改其他 pthread 中的当前目录的情况下更改 pthread 中的当前目录,我找到了一个使用 openat() 函数的解决方案,但我没有找到任何解释它如何工作的示例。 使用
是否可以通过任何方式更改进程可以创建的 pthread 数量限制? 目前在我的 linux 系统上我可以创建大约 380 个线程,但我想增加它,只要内存可用。 最佳答案 减少用户的堆栈大小' ulim
问候。我正在尝试创建一个 autoconf 配置脚本,该脚本自动检查要使用的 pthread 选项,并且理想情况下,在使用 gcc 编译时指定 -pthread。 我希望 AX_PTHREAD 能够工
如何知道 pthread 是否死亡? 有办法检查 pthread 状态吗? 最佳答案 if(pthread_kill(the_thread, 0) == 0) { /* still runni
我正在从一个由互斥锁控制的固定大小的全局池中分配我的 pthread 线程特定数据。 (有问题的代码不允许动态分配内存;它允许使用的所有内存都由调用者作为单个缓冲区提供。pthreads 可能会分配内
在阅读了一些 MPI 规范后,我了解到,当使用 MPI_THREAD_SERIALIZED 进行初始化时,程序必须确保发生在不同线程中的 MPI_Send/Recv 调用不能重叠。换句话说,您需要一个
我尝试根据 this guide 安装 pthread win32 . 我将 pthreadVC2.dll 文件添加到 C:\Windows 并将 pthreadVC2.lib 文件添加到 C:\Pr
我有一个 pthreads 程序。我必须使用 Linux 中的 gcc -pthread(-pthreads 是无法识别的选项)和 Sun 中的 gcc -pthreads(-pthread 是无法识
我有一个包含文件名列表的文件,我想在其中搜索一个词并替换它我稍微修改了代码只是为了在这里只显示相关部分问题是如果我在该列表中只有一个文件,它不会用多线程处理它,因为线程只有在我有多个文件时才工作所以我
我正在编写一个 SMT 程序,并且正在尝试解决一个有趣的问题。 我需要所有函数一起退出,但是有些线程卡在障碍物上,即使我不希望它们这样做。 我的问题是:当我删除障碍时会发生什么?卡在屏障处的线程会释放
我阅读了有关 pthread 及其相关 API 的所有内容,以创建、锁定和同步不同的线程。但我经常发现线程池、消费者/生产者等词提示。我理解这些是 pthread 实现的模型。 任何人都可以让我知道
我在 man pthread_join 中读到,多个 pthread 不能加入一个已经加入的 pthread。还有另一种方法可以达到相同的结果吗?多个 pthread 挂起自己,直到某个特定的 pth
我知道 OpenMP 实际上只是一组编译成 pthread 的宏。有没有办法在编译的其余部分发生之前查看 pthread 代码?我正在使用 GCC 进行编译。 最佳答案 首先,OpenMP 不是一组简
我是一名优秀的程序员,十分优秀!