罗_________http和多线程程序示例

http和多线程程序示例


这里写图片描述

这次要说的是利用http和多线程实现一个矩阵向量乘法运算。使用如此曲折的办法来计算可能有点小题大做。但是距离真正的大型可用算法还远:
这次涉及的要点有:

  • cgi程序的配置
  • 多线程p_thread接口的多个函数参数的传递
  • 使用socket做http请求客户端

有待解决的难点:

  • 如何用c++程序做一个简单的http server(这样就可以提供一个更灵活的http接口了)
  • 如何在socket做http请求时使用url传参?

服务器端程序,放在Apache服务器的www文件夹的cgi-bin下:

#include <iostream>
#include <pthread.h>
#include <vector>

#define MAX_NUM_THREADS 2

using namespace std;

template<class DType>
struct Dot
{
    vector<DType> VEC;
    vector<vector<DType> > MAT;
    vector<DType> RES;
};

Dot<float> dot;


template<class DType>
//void* multi_matrix(const vector<DType> VEC,const vector<vector<DType> > MAT,vector<DType>& RES,const int op_dim)
void* multi_matrix(Dot<DType>& dot,const int op_dim)
{
    if (dot.VEC.size() != dot.MAT[0].size())
    {
        cout<<" Error! dim must be the same "<<endl;
    }
    DType res;
    for (int i = 0; i < dot.VEC.size(); ++i )
    {
        res += dot.VEC[i]*dot.MAT[op_dim][i];
    }
    dot.RES[op_dim] = res;
}


void* multi_matrix_thread(void* args)
{
    int i = *(int *)args;
    //if(i>=MAX_NUM_THREADS){return 0;}
    //cout<<i<<endl;
    multi_matrix(dot,i-1);
    return 0;
}


int main(int argc, char const *argv[])
{
    //DATA
    std::vector<float> VEC;VEC.push_back(0.5);VEC.push_back(0.4);VEC.push_back(0.3);VEC.push_back(0.7);
    std::vector<std::vector<float> > MAT;MAT.push_back(VEC);MAT.push_back(VEC);
    std::vector<float> RES;RES.push_back(0);RES.push_back(0);
    dot.MAT = MAT;dot.VEC = VEC;dot.RES = RES;

    //Compute
    pthread_t tids[MAX_NUM_THREADS];
    for(int i=0;i<MAX_NUM_THREADS;++i)
    {
        int ret = pthread_create(&tids[i],NULL,multi_matrix_thread,&i);
        if(ret!=0)
        {
           cout<<" pthread_create error: error code = "<<ret<<endl;
        }
    }
    //pthread_exit(NULL);

    //PRINT
    cout<<"Content-type:text/html\r\n\r\n";
    cout<<"result: "<<dot.RES[0]<<", "<<dot.RES[1]<<" ..."<<endl;

    pthread_exit(NULL);
    return 0;
}

编译语句:

[root@master cgi-bin]# g++ multi.cpp -lpthread -o test.cgi

请求程序:

#include "HttpRequest.h"

int main()
{
    HttpRequest* Http = new HttpRequest;

    char* str = (char*)malloc(BUFSIZE);

    memset(str, 0, BUFSIZE);    
    if(Http->HttpGet("127.0.0.1/test.cgi", str)) {
        printf("%s\n", str);
    } else {
        printf("127.0.0.1 HttpGet请求失败!\n");
    }




    free(str);
    return 0;
}

所有代码我放在github上:
https://github.com/Luomin1993/Http-and-Matrix
可以下载编译运行一下… …

运行结果:

[root@master cgi-bin]# ./HttpTest 
Content-type:text/html

result: 0.99, 0.99 ...

猜你喜欢

转载自blog.csdn.net/hanss2/article/details/79448024
今日推荐