[英]Thread move in C++11
我在Action中測試C ++並發中的示例時遇到了一些問題。
/***
Scoped_thread
Help explain the move semantics of Scoped_guard
@c++ Concurrency in Action
***/
#include <thread>
#include <iostream>
using namespace std;
class Scoped_thread
{
std::thread t;
public:
Scoped_thread(std::thread _t):
t(std::move(_t))
{
cout << "Success?" << endl;
if (!t.joinable())
throw std::logic_error("No thread");
}
~Scoped_thread()
{
t.join();
}
Scoped_thread(Scoped_thread const&) = delete;
Scoped_thread& operator=(Scoped_thread const&) = delete;
};
struct func
{
int& i;
func(int& i):i(i) {}
void operator()()
{
for (unsigned j = 0; j < 1000000; j++)
{
cout << j << endl;
}
}
};
int main()
{
int some_local_state = 1;
func myfunc(some_local_state);
Scoped_thread t2(std::thread(myfunc));
for (unsigned j = 0; j < 1000; j++)
{
cout << "Main thread " << j << endl;
}
}
打印時,只出現“主線程”。 我發現構造函數沒有啟動。 這表明使用線程移動語義有些問題嗎? 我的工作環境是Ubuntu 16.04,編譯命令是'g ++ -std = c ++ 11 -Wall -pthread file.cpp'
Scoped_thread t2(std::thread(myfunc));
在這里,我們有一個稍微非常規的最煩惱的解析案例。 問題是:以下函數轉發聲明是等效的:
void f(int arg);
void f(int (arg));
因此, Scoped_thread t2(std::thread(myfunc));
被解析為函數t2
的前向聲明,返回Scoped_thread
並將std::thread myfunc
作為參數。
兩個解決方案是:
Scoped_thread t2{std::thread(myfunc)};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.