c++11 之后在STL中引入了thread
#include <iostream>
#include <thread>
void foo()
{
std::cout << "foo thread thread id: " << std::this_thread::get_id() << '\n';
}
void bar(int x)
{
std::cout << "bar thread thread id: " << std::this_thread::get_id() << '\n';
}
int main()
{
std::thread first(foo);
std::thread second(bar, 0);
std::cout << "main thread id: " << std::this_thread::get_id() << '\n';
first.join();
second.join();
std::cout << "main end\n";
return 0;
}
#include <iostream>
#include <thread>
#include <chrono>
std::thread::id main_thread_id = std::this_thread::get_id();
void is_main_thread()
{
if (main_thread_id == std::this_thread::get_id())
std::cout << "This is the main thread.\n";
else
std::cout << "This is no the main thread.\n";
}
int main()
{
is_main_thread();
std::thread th(is_main_thread);
th.join();
return 0;
}
#include <iostream>
#include <thread>
#include <chrono>
void pause_thread(int n)
{
std::this_thread::sleep_for(std::chrono::seconds(n));
std::cout << "pause of " << n << " seconds ended\n";
}
int main()
{
std::cout << "Spawning and detaching 3 threads...\n";
std::thread(pause_thread, 1).detach();
std::thread(pause_thread, 2).detach();
std::thread(pause_thread, 3).detach();
std::cout << "Done spawning threads.\n";
std::cout << "(the main thread will now pause for 5 seconds)\n";
pause_thread(5);
return 0;
}
/*
output:
Spawning and detaching 3 threads...
Done spawning threads.
(the main thread will now pause for 5 seconds)
pause of 1 seconds ended
pause of 2 seconds ended
pause of 3 seconds ended
pause of 5 seconds ended
*/
#include <iostream>
#include <thread>
void mythread()
{
std::cout << "mythread\n";
}
int main()
{
std::thread foo;
std::thread bar(mythread);
std::cout << "Joinable after construction:\n" << std::boolalpha;
std::cout << "foo: " << foo.joinable() << '\n';
std::cout << "bar: " << bar.joinable() << '\n';
if (foo.joinable())
foo.join();
if (bar.joinable())
bar.join();
std::cout << "Joinable after construction:\n" << std::boolalpha;
std::cout << "foo: " << foo.joinable() << '\n';
std::cout << "bar: " << bar.joinable() << '\n';
return 0;
}
/*
output:
mythread
Joinable after construction:
foo: false
bar: true
Joinable after construction:
foo: false
bar: false
*/
返回第一个为true的元素。
找不到则返回最后一个元素。
#include <iostream>
#include <algorithm>
#include <vector>
bool IsOdd(int i)
{
return ((i % 2) == 1);
}
int main()
{
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if(myvector.begin(), myvector.end(), IsOdd);
std::cout << "The first odd value is " << *it << '\n'; //25
return 0;
}
#include <iostream>
#include <functional>
double my_divide(double x, double y)
{
return x / y;
}
struct MyPair
{
double a;
double b;
double multiply()
{
return a * b;
}
};
int main()
{
using namespace std::placeholders;
auto fn_five = std::bind(my_divide, 10, 2); //return 10/2
std::cout << fn_five() << "\n";
auto fn_half = std::bind(my_divide, _1, 2); //return x/2
std::cout << fn_half(10) << "\n";
auto fn_invert = std::bind(my_divide, _2, _1); //return y/x
std::cout << fn_invert(10, 2) << '\n';
auto fn_rounding = std::bind<int>(my_divide, _1, _2); //return int(10/3)
std::cout << fn_rounding(10, 3) << "\n";
MyPair ten_two{ 10, 2 };
auto bound_member_fn = std::bind(&MyPair::multiply, _1); //return x.multiply()
std::cout << bound_member_fn(ten_two) << '\n';
auto bound_member_data = std::bind(&MyPair::a, ten_two); //return ten_two.a
std::cout << bound_member_data() << '\n';
auto bound_member_data_2 = std::bind(&MyPair::a, _1); //return x.a
std::cout << bound_member_data(ten_two) << '\n';
return 0;
}
#include <iostream>
#include <functional>
std::function<size_t(const char*)> print_func;
size_t CPrint(const char * pcStr)
{
std::cout << pcStr << '\n';
return 0;
}
class CxxPrint
{
public:
size_t operator()(const char * pcStr)
{
std::cout << pcStr << '\n';
return 0;
}
};
int main()
{
print_func = CPrint;
print_func("Hello World");
CxxPrint p;
print_func = p;
print_func("Hello CxxPrint");
return 0;
}
#include <iostream>
#include <algorithm>
#include <vector>
#include <functional>
// 4. capture of class member
class A
{
public:
//capture member by this
void DoSomethins1()
{
auto it = std::find_if(m_vec.begin(), m_vec.end(), [this](int i) {
return i > m_min_val && i < m_max_val;
});
}
//capture member by default pass-by-value
void DoSomethins2()
{
auto it = std::find_if(m_vec.begin(), m_vec.end(), [=](int i) {
return i > m_min_val && i < m_max_val;
});
}
//capture member by default pass-by-reference
void DoSomethins3()
{
auto it = std::find_if(m_vec.begin(), m_vec.end(), [&](int i) {
return i > m_min_val && i < m_max_val;
});
}
private:
std::vector<int> m_vec;
int m_min_val;
int m_max_val;
};
int main()
{
//1. simple lambda
std::vector<int> myvector;
myvector.push_back(10);
myvector.push_back(25);
myvector.push_back(40);
myvector.push_back(55);
std::vector<int>::iterator it = std::find_if(myvector.begin(), myvector.end(), [](int i) {
return ((i % 2) == 1);
});
std::cout << "The first odd value is " << *it << '\n'; //25
//2. lambda return syntax
std::function<int(int)> square = [](int i) -> int { return i * i; };
std::cout << square(10) << "\n";
//3. capture of local variable
/*
[a,&b] 其中 a 以复制捕获而 b 以引用捕获。
[this] 以引用捕获当前对象( *this )
[&] 以引用捕获所有用于 lambda 体内的自动变量,并以引用捕获当前对象,若存在
[=] 以复制捕获所有用于 lambda 体内的自动变量,并以引用捕获当前对象,若存在
[] 不捕获
*/
{
int min_val = 10;
int max_val = 100;
auto it = std::find_if(myvector.begin(), myvector.end(), [=](int i) {
return i > min_val && i < max_val;
});
auto it1 = std::find_if(myvector.begin(), myvector.end(), [&](int i) {
return i > min_val && i < max_val;
});
auto it2 = std::find_if(myvector.begin(), myvector.end(), [=, &max_val](int i) {
return i > min_val && i < max_val;
});
}
return 0;
}
vector 可以动态的变大。
array 是固定大小的,就是一个普通的数组,可以使用迭代器。
#include <iostream>
#include <array>
std::array<int, 3> global; //initialized as: {0,0,0}
int main()
{
std::array<int, 3> first; //uninitialized
std::array<int, 3> second = { 10, 20 }; //initialized as: {10,20,0}
std::array<int, 3> third = { 1, 2, 3 }; //initialized as: {1,2,3}
std::array<int, 3> fourth = third;
for (auto x : fourth)
std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
返回一个引用。
#include <iostream>
#include <array>
int main()
{
std::array<int, 10> myarray;
for (int i = 0; i < 10; i++)
myarray.at(i) = i + 1;
std::cout << "myarray contains:";
for (int i = 0; i < 10; i++)
std::cout << ' ' << myarray.at(i);
std::cout << '\n';
return 0;
}
front() 返回第一个元素的引用。
back() 返回最后一个元素的引用。
#include <iostream>
#include <array>
int main()
{
std::array<int, 3> myarray = { 2, 16, 77 };
std::cout << "front is: " << myarray.front() << std::endl;
std::cout << "back is: " << myarray.back() << std::endl;
myarray.front() = 100;
myarray.back() = 99;
for (int & x : myarray)
std::cout << ' ' << x;
std::cout << '\n';
return 0;
}
#include <iostream>
#include <array>
int main()
{
std::array<int, 5> myarray = { 2, 16, 77, 34, 50 };
for (auto it = myarray.begin(); it != myarray.end(); ++it)
{
std::cout << ' ' << *it;
}
std::cout << '\n';
return 0;
}
size() 和 max_size() 好像是一样的。
#include <iostream>
#include <array>
int main()
{
std::array<int, 10> myints;
std::cout << "size of myints: " << myints.size() << std::endl; //10
std::cout << "max_size of myints: " << myints.max_size() << std::endl; //10
std::cout << "sizeof(myints): " << sizeof(myints) << std::endl; //40
return 0;
}
返回指向第一个元素的指针。
#include <iostream>
#include <cstring>
#include <array>
int main()
{
const char * cstr = "Test string";
std::array<char, 12> charray;
std::memcpy(charray.data(), cstr, 12);
std::cout << charray.data() << '\n';
return 0;
}
#include <iostream>
#include <array>
int main()
{
std::array<int, 10> myarray;
unsigned int i;
for (i = 0; i < 10; i++)
myarray[i] = i;
for (i = 0; i < 10; i++)
std::cout << ' ' << myarray[i];
std::cout << '\n';
return 0;
}
#include <iostream>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
int main(int argc, char * argv[])
{
try
{
if (argc != 2)
{
std::cerr << "Usage: client <host>" << std::endl;
return 1;
}
boost::asio::io_service io_service;
udp::resolver resolver(io_service);
udp::resolver::query query(udp::v4(), argv[1], "daytime");
udp::endpoint receiver_endpoint = *resolver.resolve(query);
udp::socket socket(io_service);
socket.open(udp::v4());
boost::array<char, 1> send_buf = { {0} };
socket.send_to(boost::asio::buffer(send_buf), receiver_endpoint);
boost::array<char, 128> recv_buf;
udp::endpoint sender_endpoint;
size_t len = socket.receive_from(boost::asio::buffer(recv_buf), sender_endpoint);
std::cout.write(recv_buf.data(), len);
}
catch (std::exception & e)
{
std::cerr << "catch error: " << e.what() << std::endl;
}
return 0;
}
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
std::string make_daytime_string()
{
using namespace std;
time_t now = time(0);
return ctime(&now);
}
int main(int argc, char * argv[])
{
try
{
boost::asio::io_service io_service;
udp::socket socket(io_service, udp::endpoint(udp::v4(), 13));
for (;;)
{
boost::array<char, 1> recv_buf;
udp::endpoint remote_endpoint;
boost::system::error_code error;
socket.receive_from(boost::asio::buffer(recv_buf),
remote_endpoint, 0, error);
if (error && error != boost::asio::error::message_size)
throw boost::system::system_error(error);
std::string message = make_daytime_string();
boost::system::error_code ignored_error;
socket.send_to(boost::asio::buffer(message),
remote_endpoint, 0, ignored_error);
}
}
catch (std::exception & e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::udp;
std::string make_daytime_string()
{
using namespace std;
time_t now = time(0);
return ctime(&now);
}
class udp_server
{
public:
udp_server(boost::asio::io_service & io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_),
remote_endpoint,
boost::bind(&udp_server::handle_receive,
this,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
}
void handle_receive(const boost::system::error_code & error, std::size_t)
{
if (!error || error == boost::asio::error::message_size)
{
boost::shared_ptr<std::string> message(
new std::string(make_daytime_string())
);
socket_.async_send_to(
boost::asio::buffer(*message),
remote_endpoint,
boost::bind(&udp_server::handle_send,
this,
message,
boost::asio::placeholders::error,
boost::asio::placeholders::bytes_transferred)
);
start_receive();
}
}
void handle_send(boost::shared_ptr<std::string>,
const boost::system::error_code &,
std::size_t)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint;
boost::array<char, 1> recv_buffer_;
};
int main()
{
try
{
boost::asio::io_service io_service;
udp_server server(io_service);
io_service.run();
}
catch (std::exception & e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}
#include <ctime>
#include <iostream>
#include <string>
#include <boost/array.hpp>
#include <boost/bind.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/asio.hpp>
using boost::asio::ip::tcp;
using boost::asio::ip::udp;
std::string make_daytime_string()
{
using namespace std; // For time_t, time and ctime;
time_t now = time(0);
return ctime(&now);
}
class tcp_connection
: public boost::enable_shared_from_this<tcp_connection>
{
public:
typedef boost::shared_ptr<tcp_connection> pointer;
static pointer create(boost::asio::io_service& io_service)
{
return pointer(new tcp_connection(io_service));
}
tcp::socket& socket()
{
return socket_;
}
void start()
{
message_ = make_daytime_string();
boost::asio::async_write(socket_, boost::asio::buffer(message_),
boost::bind(&tcp_connection::handle_write, shared_from_this()));
}
private:
tcp_connection(boost::asio::io_service& io_service)
: socket_(io_service)
{
}
void handle_write()
{
}
tcp::socket socket_;
std::string message_;
};
class tcp_server
{
public:
tcp_server(boost::asio::io_service& io_service)
: acceptor_(io_service, tcp::endpoint(tcp::v4(), 13))
{
start_accept();
}
private:
void start_accept()
{
tcp_connection::pointer new_connection =
tcp_connection::create(acceptor_.get_io_service());
acceptor_.async_accept(new_connection->socket(),
boost::bind(&tcp_server::handle_accept, this, new_connection,
boost::asio::placeholders::error));
}
void handle_accept(tcp_connection::pointer new_connection,
const boost::system::error_code& error)
{
if (!error)
{
new_connection->start();
}
start_accept();
}
tcp::acceptor acceptor_;
};
class udp_server
{
public:
udp_server(boost::asio::io_service& io_service)
: socket_(io_service, udp::endpoint(udp::v4(), 13))
{
start_receive();
}
private:
void start_receive()
{
socket_.async_receive_from(
boost::asio::buffer(recv_buffer_), remote_endpoint_,
boost::bind(&udp_server::handle_receive, this,
boost::asio::placeholders::error));
}
void handle_receive(const boost::system::error_code& error)
{
if (!error || error == boost::asio::error::message_size)
{
boost::shared_ptr<std::string> message(
new std::string(make_daytime_string()));
socket_.async_send_to(boost::asio::buffer(*message), remote_endpoint_,
boost::bind(&udp_server::handle_send, this, message));
start_receive();
}
}
void handle_send(boost::shared_ptr<std::string> /*message*/)
{
}
udp::socket socket_;
udp::endpoint remote_endpoint_;
boost::array<char, 1> recv_buffer_;
};
int main()
{
try
{
boost::asio::io_service io_service;
tcp_server server1(io_service);
udp_server server2(io_service);
io_service.run();
}
catch (std::exception& e)
{
std::cerr << e.what() << std::endl;
}
return 0;
}