如何正确使用移动语义与对象中的运行线程?
样品:
#include <iostream>
#include <thread>
#include <vector>
struct A {
std::string v_;
std::thread t_;
void start() {
t_ = std::thread(&A::threadProc, this);
}
void threadProc() {
for(;;) {
std::cout << "foo-" << v_ << '\n';
std::this_thread::sleep_for(std::chrono::seconds(5));
}
}
};
int main() {
A m;
{
A a;
a.v_ = "bar";
a.start();
m = std::move(a);
}
std::cout << "v_ = " << m.v_ << '\n'; /* stdout is 'v_ = bar' as expected */
/* but v_ in thread proc was …Run Code Online (Sandbox Code Playgroud) 我有双向流异步 grpc 客户端,它使用 ClientAsyncReaderWriter 与服务器进行通信。RPC 代码如下所示:
rpc Process (stream Request) returns (stream Response)
Run Code Online (Sandbox Code Playgroud)
为简单起见,请求和响应是字节数组(byte[] )。我向服务器发送了几块数据,当服务器积累了足够的数据时,服务器处理这些数据并发回响应并继续为下一个响应积累数据。经过多次响应,服务器发送最终响应并关闭连接。
对于异步客户端,我使用CompletionQueue. 代码如下:
...
CompletionQueue cq;
std::unique_ptr<Stub> stub;
grpc::ClientContext context;
std::unique_ptr<grpc::ClientAsyncReaderWriter<Request,Response>> responder = stub->AsyncProcess(&context, &cq, handler);
// thread for completition queue
std::thread t(
[]{
void *handler = nullptr;
bool ok = false;
while (cq_.Next(&handler, &ok)) {
if (can_read) {
// how do you know that it is read data available
// Do read
} else {
// do write
...
Request request = …Run Code Online (Sandbox Code Playgroud) 像这样在循环中创建线程是否不好?
线程函数示例:
void *thread_func(void* args)
{
const char *str = (const char *)args;
printf("Threading %s\n", str);
usleep(1000);
}
Run Code Online (Sandbox Code Playgroud)
主循环:
pthread_t thread;
while (1) {
char *str = "test str";
if (pthread_create(&thread, NULL, thread_func, str)) {
fprintf(stderr, "Failed to create thread\n");
return -1;
}
usleep(3000);
/* Thread guaranteed finished here */
}
Run Code Online (Sandbox Code Playgroud)
或者我必须创建一次并循环使用