lib-zo,C语言另一个协程库,激活文件IO操作协程化
lib-zo,C语言另一个协程库,激活文件IO操作协程化
另一个 C 协程库 https://blog.csdn.net/eli960/article/details/146802313
支持文件IO协程化的函数列表,请查看:
https://blog.csdn.net/eli960/article/details/146802313
支持文件IO操作协程化
关键开关:
// 设置协程阻塞线程的数量限制为3
zvar_coroutine_block_pthread_count_limit = 3;
// 启用协程文件IO使用阻塞线程
zvar_coroutine_fileio_use_block_pthread = 1;
一般模型
// 包含协程相关的头文件
#include "coroutine.h"
static void *file_do(void *arg)
{
// 在这里操作open/read/write, 就都是协程化的
}
int main(int argc, char **argv)
{
int i;
// 初始化协程库
zcoroutine_base_init();
// 设置协程阻塞线程的数量限制为3
zvar_coroutine_block_pthread_count_limit = 3;
// 启用协程文件IO使用阻塞线程
zvar_coroutine_fileio_use_block_pthread = 1;
// 启动一个新的协程执行 file_do 函数
zcoroutine_go(file_do, 0, 0);
// 启动协程库运行
zcoroutine_base_run();
// 清理协程库资源
zcoroutine_base_fini();
return 0;
}
文件IO协程化例子
注意: 下面例子, 函数 file_do 中, 用到的 open/write/lseek/close/sleep 等都是协程化的
/*
* ================================
* eli960@qq.com
* http://linuxmail.cn/
* 2018-07-10
* ================================
*/
// 包含协程相关的头文件
#include "coroutine.h"
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/syscall.h>
#include <fcntl.h>
// 静态变量,用于记录当前运行的协程数量
static int co_count = 0;
/**
* @brief 协程执行的文件操作函数
*
* 该函数会打开一个名为 "a.txt" 的文件,向文件中写入数据,
* 然后将文件指针重置到文件开头,重复该过程100次。
* 每次操作完成后会休眠1秒。当所有协程都完成操作后,会通知协程库停止运行。
*
* @param arg 传递给协程的参数,在本函数中未使用
* @return void* 函数返回值,固定返回0
*/
static void *file_do(void *arg)
{
// 定义要操作的文件名
char *fn = "a.txt";
// 以读写模式打开文件,如果文件不存在则创建,同时截断文件内容
int fd = open(fn, O_RDWR|O_CREAT|O_TRUNC, 0777);
// 检查文件是否成功打开
if (fd == -1) {
// 若打开失败,输出错误信息
fprintf(stderr, "can not open %s(%m)\n", fn);
return 0;
}
// 循环100次,向文件中写入数据并重置文件指针
for (int i=0;i < 100; i++) {
// 向文件中写入8字节的数据
if (write(fd, "0123456789", 8) != 8) {
// 若写入失败,输出错误信息
fprintf(stderr, "write error\n");
}
// 将文件指针重置到文件开头
if (lseek(fd, 0, SEEK_SET) == (off_t)-1) {
// 若重置失败,输出错误信息
fprintf(stderr, "lseek error (%m)");
}
// 休眠1秒
sleep(1);
}
// 关闭文件
close(fd);
// 协程完成操作,协程数量减1
co_count--;
// 检查是否所有协程都已完成操作
if (co_count == 0) {
// 若所有协程都已完成,输出通知信息
fprintf(stderr, "zcoroutine_base_stop_notify\n");
// 通知协程库停止运行
zcoroutine_base_stop_notify(0);
}
return 0;
}
/**
* @brief 程序入口函数
*
* 初始化协程库,设置协程相关的参数,创建多个协程执行文件操作,
* 然后启动协程库运行,最后清理协程库资源。
*
* @param argc 命令行参数的数量
* @param argv 命令行参数的数组
* @return int 程序的退出状态码,固定返回0
*/
int main(int argc, char **argv)
{
int i;
// 初始化协程库
zcoroutine_base_init();
// 设置协程阻塞线程的数量限制为3
zvar_coroutine_block_pthread_count_limit = 3;
// 启用协程文件IO使用阻塞线程
zvar_coroutine_fileio_use_block_pthread = 1;
// 设置要创建的协程数量为10
co_count = 10;
// 循环创建协程
for (i=0;i<co_count;i++) {
// 启动一个新的协程执行 file_do 函数
zcoroutine_go(file_do, 0, 0);
}
// 输出提示信息,表示程序将在100秒后退出
printf("exit after 100s\n");
// 输出提示信息,表示文件IO操作在工作线程中运行
printf("file io running in worker pthread\n");
// 输出提示信息,建议使用 strace 命令跟踪线程
printf("strace -p pthrad_id\n");
// 启动协程库运行
zcoroutine_base_run();
// 清理协程库资源
zcoroutine_base_fini();
// 休眠1秒
sleep(1);
return 0;
}