我想用c ++创建多线程mjpeg流,我用单线程成功,但是当我尝试启动" stream"函数在一个单独的线程中或使用std :: async(我认为async比在这种情况下创建一个线程更好),我不明白为什么,它不起作用。那个函数似乎不是从其他线程开始的。你能帮帮我吗?感谢
streamer.cpp
#include "streamer.h"
#include <cstring>
#include <sys/types.h>
#include <unistd.h>
#include <future>
void Streamer::stream(int socket)
{
std::string image, buffer;
int check = send(socket, header.c_str(), header.size(), MSG_NOSIGNAL);
while (check > 0)
{
image = camera->getFrameInByteArray();
buffer = "--boundary\r\n"
"Content-Type: image/jpeg\r\n"
"Content-Length: " + std::to_string(image.size()) + "\r\n\r\n" + image;
check = send(socket, buffer.c_str(), buffer.size(), MSG_NOSIGNAL);
}
close(socket);
}
void Streamer::start() {
bindChannel();
listen(socketFileDescriptor, 5);
socklen_t clientLenght = sizeof(clientAddress);
while(1) {
newSocketFileDescriptor = accept(socketFileDescriptor, (struct sockaddr *) &clientAddress, &clientLenght);
if (newSocketFileDescriptor < 0)
error("Error accepting request");
/*If I do this, I can't serve more than one request*/
std::async(std::launch::async, &Streamer::stream, this, newSocketFileDescriptor);
}
close(socketFileDescriptor);
}
void Streamer::error(std::string msg){...}
void Streamer::bindChannel(){...}
Streamer::~Streamer(){...}
Streamer::Streamer(int port, int cameraAddress){...}
编辑:
我尝试以这种方式定义为static和modify stream()函数:
void Streamer::stream(Camera &cam, int socket)
{
std::string head = "HTTP/1.1 200 OK\r\n"
"Connection: close\r\n"
"Max-Age: 0\r\n"
"Expires: 0\r\n"
"Cache-Control: no-cache, private\r\n"
"Pragma: no-cache\r\n"
"Content-Type: multipart/x-mixed-replace;boundary=--boundary\r\n\r\n";
std::string image, buffer;
int check = send(socket, head.c_str(), head.size(), MSG_NOSIGNAL);
while (check > 0)
{
image = cam.getFrameInByteArray();
buffer = "--boundary\r\n"
"Content-Type: image/jpeg\r\n"
"Content-Length: " + std::to_string(image.size()) + "\r\n\r\n" + image;
check = send(socket, buffer.c_str(), buffer.size(), MSG_NOSIGNAL);
}
close(socket);
}
我试过这些:
//std::thread{Streamer::stream, std::ref(*camera), newSocketFileDescriptor}.detach();
//auto f = std::async(std::launch::async, Streamer::stream, std::ref(*camera), newSocketFileDescriptor);
//std::async(std::launch::async, Streamer::stream, std::ref(*camera), newSocketFileDescriptor);
在所有情况下,我一次只能提供一个请求