写两个c语言接口实现设置某类消息发送间隔
时间: 2024-03-06 18:06:18 浏览: 19
这里提供两个C语言接口示例,用于设置某类消息发送间隔:
1. 使用结构体保存消息发送间隔
```c
typedef struct {
int msg_type;
int interval;
} MsgInterval;
// 设置某类消息的发送间隔
void set_msg_interval(MsgInterval* intervals, int size, int msg_type, int interval) {
for (int i = 0; i < size; i++) {
if (intervals[i].msg_type == msg_type) {
intervals[i].interval = interval;
return;
}
}
// 如果该类消息的间隔还未设置,则新增一项
intervals[size].msg_type = msg_type;
intervals[size].interval = interval;
}
// 获取某类消息的发送间隔
int get_msg_interval(MsgInterval* intervals, int size, int msg_type) {
for (int i = 0; i < size; i++) {
if (intervals[i].msg_type == msg_type) {
return intervals[i].interval;
}
}
// 如果该类消息的间隔还未设置,则返回默认值
return DEFAULT_INTERVAL;
}
```
2. 使用哈希表保存消息发送间隔
```c
#define TABLE_SIZE 100
// 哈希表节点
typedef struct Node {
int msg_type;
int interval;
struct Node* next;
} Node;
// 哈希表
typedef struct {
Node* table[TABLE_SIZE];
} MsgIntervalTable;
// 计算哈希值
unsigned int hash(unsigned int x) {
return (x * 2654435761) % TABLE_SIZE;
}
// 设置某类消息的发送间隔
void set_msg_interval(MsgIntervalTable* table, int msg_type, int interval) {
unsigned int index = hash(msg_type);
Node* node = table->table[index];
while (node) {
if (node->msg_type == msg_type) {
node->interval = interval;
return;
}
node = node->next;
}
// 如果该类消息的间隔还未设置,则新增一项
Node* new_node = (Node*)malloc(sizeof(Node));
new_node->msg_type = msg_type;
new_node->interval = interval;
new_node->next = table->table[index];
table->table[index] = new_node;
}
// 获取某类消息的发送间隔
int get_msg_interval(MsgIntervalTable* table, int msg_type) {
unsigned int index = hash(msg_type);
Node* node = table->table[index];
while (node) {
if (node->msg_type == msg_type) {
return node->interval;
}
node = node->next;
}
// 如果该类消息的间隔还未设置,则返回默认值
return DEFAULT_INTERVAL;
}
```
这两个接口都可以实现设置某类消息的发送间隔,具体选择哪个接口取决于项目的具体情况。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)