add original source
This commit is contained in:
56
source/listing_2.6.cpp
Normal file
56
source/listing_2.6.cpp
Normal file
@@ -0,0 +1,56 @@
|
||||
#include <thread>
|
||||
#include <utility>
|
||||
|
||||
class scoped_thread
|
||||
{
|
||||
std::thread t;
|
||||
public:
|
||||
explicit scoped_thread(std::thread t_):
|
||||
t(std::move(t_))
|
||||
{
|
||||
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;
|
||||
};
|
||||
|
||||
void do_something(int& i)
|
||||
{
|
||||
++i;
|
||||
}
|
||||
|
||||
struct func
|
||||
{
|
||||
int& i;
|
||||
|
||||
func(int& i_):i(i_){}
|
||||
|
||||
void operator()()
|
||||
{
|
||||
for(unsigned j=0;j<1000000;++j)
|
||||
{
|
||||
do_something(i);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
void do_something_in_current_thread()
|
||||
{}
|
||||
|
||||
void f()
|
||||
{
|
||||
int some_local_state;
|
||||
scoped_thread t(std::thread(func(some_local_state)));
|
||||
|
||||
do_something_in_current_thread();
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
f();
|
||||
}
|
||||
Reference in New Issue
Block a user