g_JavaVM->AttachCurrentThread((void **) &pEnv, NULL))返回-1

g_JavaVM->AttachCurrentThread((void **) &pEnv, NULL))返回-1,流式回调问题解决了,因为研究院流式回调线程从pthread改成了brpc的bthread,jvm和bthread不兼容,导致无法绑定线程;解决方法是将回调结果缓存到任务队列,起个pthread线程消费队列,往上层发;

特性

pthread (POSIX Threads)

bthread (BRPC)

线程模型

1:1(内核线程)

M:N(用户态线程,映射到少量pthread)

创建开销

较高(微秒级,需内核参与)

极低(纳秒级,纯用户态操作)

调度方式

由操作系统内核调度

用户态协作式调度(Work-Stealing算法)

阻塞影响

阻塞整个内核线程

仅阻塞当前bthread(自动切换其他任务)

内存占用

每个线程独立栈(默认MB级)

共享栈池(默认KB级)

多核利用率

依赖OS调度

自动负载均衡

//线程
std::queue<SourceResult> queue;
std::atomic<bool> stop_flag;
pthread_mutex_t pmutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t pcond = PTHREAD_COND_INITIALIZER;
pthread_t consumer;
// 消费者成员函数
void CtaT4Impl::consume() {
    while (stop_flag==false) {
        
        pthread_mutex_lock(&pmutex);
        // 无任务时等待
        while (queue.size() == 0 && stop_flag==false)
        {
            pthread_cond_wait(&pcond, &pmutex);//等待并释放锁
        }
        // 处理所有待执行任务
        while (queue.size() > 0&& stop_flag==false) {
            SourceResult task = queue.front();
            queue.pop();
            pthread_mutex_unlock(&pmutex);  // 执行任务时释放锁
            if (pTaskEvent_)
            {
                pTaskEvent_->OnFinished(task);
                VCAENGINE_INFO("consume callback task%s", task.result.c_str());
                //std::this_thread::sleep_for(std::chrono::microseconds(10));//sleep试下,太快会出现错误JavaVM can't attach current thread
            }
            pthread_mutex_lock(&pmutex);
        }
        pthread_mutex_unlock(&pmutex);
    }
}
//线程函数
HPR_VOIDPTR CALLBACK ComsumeThread(HPR_VOIDPTR ppoint)
{
    if (ppoint == NULL)
    {
        VCAENGINE_ERROR("ppoint is NULL");
        return NULL;
    }
    CtaT4Impl* piplm = (CtaT4Impl*)ppoint;
    if (piplm == NULL)
    {
        VCAENGINE_ERROR("piplm is NULL");
        return NULL;
    }
    piplm->consume();
}
构造函数中启动消费者线程
// 启动消费者线程 (使用lambda)
stop_flag = false;
pthread_attr_t attr;
// 初始化线程属性
pthread_attr_init(&attr);
// 设置堆栈大小(单位:字节)
if (pthread_attr_setstacksize(&attr,20*1024*1024) != 0) {
    VCAENGINE_ERROR("Failed to set stack size");
    return;
}

// 创建线程
if (pthread_create(&consumer, &attr, ComsumeThread, this) != 0) {
    VCAENGINE_ERROR("Failed to create thread");
    pthread_attr_destroy(&attr);
    return;
}
// 销毁属性对象,不用等待线程结束
pthread_attr_destroy(&attr);

 

posted @ 2025-07-21 19:50  一字千金  阅读(14)  评论(0)    收藏  举报