C++ 如何创建和同步将请求通道发送到共享数据服务器以发送和检索请求的p_线程?
我们正在课堂上学习使用posix线程。我们的任务是为多个请求通道创建一个有界缓冲区,以提取请求并将其发送到一个数据服务器 下面是类RequestChannel(为我们提供)如何发送请求:C++ 如何创建和同步将请求通道发送到共享数据服务器以发送和检索请求的p_线程?,c++,multithreading,synchronization,pthreads,posix,C++,Multithreading,Synchronization,Pthreads,Posix,我们正在课堂上学习使用posix线程。我们的任务是为多个请求通道创建一个有界缓冲区,以提取请求并将其发送到一个数据服务器 下面是类RequestChannel(为我们提供)如何发送请求: string RequestChannel::send_request(string _request) { cwrite(_request); string s = cread(); return s; } string RequestChannel::cread() { char buf[
string RequestChannel::send_request(string _request) {
cwrite(_request);
string s = cread();
return s;
}
string RequestChannel::cread() {
char buf[MAX_MESSAGE];
string s = buf;
return s;
}
string reply = chan.send_request("newthread");
我们主要制作一个叫chan的频道
RequestChannel chan("control", RequestChannel::CLIENT_SIDE);
称为“控制”,这是它发送请求的方式:
string RequestChannel::send_request(string _request) {
cwrite(_request);
string s = cread();
return s;
}
string RequestChannel::cread() {
char buf[MAX_MESSAGE];
string s = buf;
return s;
}
string reply = chan.send_request("newthread");
我们从一个control RequestChannel开始,它要求数据服务器为我们提供更多的RequestChannel
下面是DataServer.C的外观(也提供给我们)
(我在这里省略了处理其他请求,因为我现在只对创建一个新线程感兴趣)
这是我迷路的部分:
void process_newthread(RequestChannel & _channel, const string & _request) {
int error;
nthreads ++;
// -- Name new data channel
string new_channel_name = "data" + int2string(nthreads) + "_";
// cout << "new channel name = " << new_channel_name << endl;
// -- Pass new channel name back to client
_channel.cwrite(new_channel_name);
// -- Construct new data channel (pointer to be passed to thread function)
RequestChannel * data_channel = new RequestChannel(new_channel_name, RequestChannel::SERVER_SIDE);
// -- Create new thread to handle request channel
pthread_t thread_id;
cout << "starting new thread " << nthreads << endl;
if (error = pthread_create(& thread_id, NULL, handle_data_requests, data_channel)) {
fprintf(stderr, "p_create failed: %s\n", strerror(error));
}
}
我自己尝试过的解决方案:
- (制作我自己的信号量和boundedbuffer)
:: ./simpleclient
CLIENT STARTED:
Establishing control channel... done.
making boundedbufferslist
Creating channels for worker threads...
Received request : newthread
Request Channel (control) writing [newthread]in cread(), s is...uest
Request Channel (control) reads [uest]
processed cwrite : uest
Reading next request from channel (control) ...in cread(), s is...newthread
Request Channel (control) reads [newthread]
done (control).
New request is newthread
^C