使用C语言创建一个线程,在线程中实现消息队列发送消息
时间: 2024-02-06 11:12:17 浏览: 177
以下是一个示例代码,使用C语言的线程库和队列库来实现消息队列发送消息:
```c
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <unistd.h>
#include <stdbool.h>
#define QUEUE_SIZE 10
// 消息结构体
struct Message {
char content[256];
int priority;
};
// 消息队列类
struct MessageQueue {
struct Message queue[QUEUE_SIZE];
int head;
int tail;
pthread_mutex_t mutex;
pthread_cond_t cond;
};
// 初始化消息队列
void MessageQueueInit(struct MessageQueue* mq) {
mq->head = 0;
mq->tail = 0;
pthread_mutex_init(&mq->mutex, NULL);
pthread_cond_init(&mq->cond, NULL);
}
// 消息队列是否已满
bool MessageQueueIsFull(struct MessageQueue* mq) {
return (mq->tail + 1) % QUEUE_SIZE == mq->head;
}
// 消息队列是否为空
bool MessageQueueIsEmpty(struct MessageQueue* mq) {
return mq->head == mq->tail;
}
// 往消息队列中添加消息
bool MessageQueuePush(struct MessageQueue* mq, const struct Message* msg) {
pthread_mutex_lock(&mq->mutex);
while (MessageQueueIsFull(mq)) {
pthread_cond_wait(&mq->cond, &mq->mutex);
}
mq->queue[mq->tail] = *msg;
mq->tail = (mq->tail + 1) % QUEUE_SIZE;
pthread_cond_signal(&mq->cond);
pthread_mutex_unlock(&mq->mutex);
return true;
}
// 从消息队列中取出消息
bool MessageQueuePop(struct MessageQueue* mq, struct Message* msg) {
pthread_mutex_lock(&mq->mutex);
while (MessageQueueIsEmpty(mq)) {
pthread_cond_wait(&mq->cond, &mq->mutex);
}
*msg = mq->queue[mq->head];
mq->head = (mq->head + 1) % QUEUE_SIZE;
pthread_cond_signal(&mq->cond);
pthread_mutex_unlock(&mq->mutex);
return true;
}
// 消息发送函数
void SendMessage(struct MessageQueue* mq, const char* content, int priority) {
struct Message msg;
snprintf(msg.content, sizeof(msg.content), "%s", content);
msg.priority = priority;
MessageQueuePush(mq, &msg);
}
// 线程函数
void* ThreadFunc(void* arg) {
struct MessageQueue* mq = (struct MessageQueue*)arg;
while (true) {
struct Message msg;
MessageQueuePop(mq, &msg);
printf("Thread got message: %s\n", msg.content);
}
return NULL;
}
int main() {
struct MessageQueue mq;
MessageQueueInit(&mq);
pthread_t thread_id;
pthread_create(&thread_id, NULL, ThreadFunc, &mq);
// 发送一些测试消息
SendMessage(&mq, "Hello world!", 2);
SendMessage(&mq, "This is a test message.", 1);
SendMessage(&mq, "Goodbye!", 3);
pthread_join(thread_id, NULL);
return 0;
}
```
在上面的代码中,我们定义了一个`Message`结构体,它包含消息内容和优先级。然后我们定义了一个`MessageQueue`结构体,它使用一个循环队列来存储消息。我们使用`pthread_mutex_t`和`pthread_cond_t`来实现线程安全的队列。在`SendMessage`函数中,我们将消息推入队列中。在线程函数`ThreadFunc`中,我们不断地从队列中弹出消息并处理。在主函数中,我们创建了一个线程并发送一些测试消息。
阅读全文