wjq_csdn 2019-11-15 15:01 采纳率: 0%
浏览 287

Linux 回调函数与线程共同访问全局变量,但结果不一样,太诡异了

#include "stdio.h"
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
#include "CommonUtils.h"
#include "address.h"
#include "tcpserver.h"
#include "httpserver.h"
#include "httprequest.h"
#include "httpresponse.h"
#include "httpconnection.h"

using namespace std;
using namespace tnet;
using namespace std::placeholders;

//==================================================================//
//全局变量
std::vector<string> vecMessageQueque;

volatile int g_iVarTest = 0;

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
//==================================================================//

void onHandler(const HttpConnectionPtr_t& conn, const HttpRequest& request)
{
    printf("HTTP接收数据:%s\n" , request.body.c_str());

    g_iVarTest += 1;

    printf("变量值地址:%d\n" , g_iVarTest);
    //=============================================================//
    //构造应答
    HttpResponse resp;
    resp.statusCode = 200;
    resp.setContentType("text/html");
    resp.setKeepAlive(true);
    resp.enableDate();    
    resp.body.append("recvdata: success"); //json字符串
    conn->send(resp);
    //=============================================================//
}

//消息队列调度线程
void* MessageProcThread(void* lpParameter)
{
    int i = 0;
    char buffer[1024];
    while (true)
    {
        printf("消息处理数量:%d\n" , g_iVarTest);

        sleep(1);
    }
}

//消息队列调度线程
void* HttpServiceThread(void* lpParameter)
{
         TcpServer s;

        HttpServer httpd(&s);

         printf("HTTP服务启动正常...\n");

        httpd.setHttpCallback("/service/", std::bind(&onHandler, _1, _2));

        httpd.listen(Address(11181));

        s.start(4);
}

int main()
{
    //创建消息处理线程
    //========================================================//
    //传入的时候必须强制转换为void* 类型,即无类型指针
    pthread_t hMsgProcThread;
    pthread_create(&hMsgProcThread, NULL, MessageProcThread, NULL);

    //测试http服务
    //========================================================//
    pthread_t hHttpServiceThread;
    pthread_create(&hHttpServiceThread, NULL, HttpServiceThread, NULL);
    //========================================================//

    while (true )
    {
        char ch = getchar();
        if (ch =='#') break;
    }

    return 0;
}

图片说明

代码如上,g_iVarTest这个值已经改变,MessageProcThread线程访问的结果与onHandler回调的结果不一样,求高手解答以下!

  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-09 15:26
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 (关键词-电路设计)
  • ¥15 如何解决MIPS计算是否溢出
  • ¥15 vue中我代理了iframe,iframe却走的是路由,没有显示该显示的网站,这个该如何处理
  • ¥15 操作系统相关算法中while();的含义
  • ¥15 CNVcaller安装后无法找到文件
  • ¥15 visual studio2022中文乱码无法解决
  • ¥15 关于华为5g模块mh5000-31接线问题
  • ¥15 keil L6007U报错
  • ¥15 webapi 发布到iis后无法访问
  • ¥15 初学者如何快速上手学习stm32?