Thread_test.cc revision 2b2bf878
1cd139dc7SShuo Chen#include "../Thread.h"
2cd139dc7SShuo Chen
3cd139dc7SShuo Chen#include <string>
4cd139dc7SShuo Chen#include <boost/bind.hpp>
5cd139dc7SShuo Chen#include <stdio.h>
6cd139dc7SShuo Chen
7cd139dc7SShuo Chenvoid threadFunc()
8cd139dc7SShuo Chen{
9cd139dc7SShuo Chen  printf("tid=%d\n", muduo::CurrentThread::tid());
10cd139dc7SShuo Chen}
11cd139dc7SShuo Chen
12cd139dc7SShuo Chenvoid threadFunc2(int x)
13cd139dc7SShuo Chen{
14cd139dc7SShuo Chen  printf("tid=%d, x=%d\n", muduo::CurrentThread::tid(), x);
15cd139dc7SShuo Chen}
16cd139dc7SShuo Chen
172b2bf878SShuo Chenvoid threadFunc3()
182b2bf878SShuo Chen{
192b2bf878SShuo Chen  printf("tid=%d\n", muduo::CurrentThread::tid());
202b2bf878SShuo Chen  sleep(1);
212b2bf878SShuo Chen}
222b2bf878SShuo Chen
23cd139dc7SShuo Chenclass Foo
24cd139dc7SShuo Chen{
25cd139dc7SShuo Chen public:
26cd139dc7SShuo Chen  explicit Foo(double x)
27cd139dc7SShuo Chen    : x_(x)
28cd139dc7SShuo Chen  {
29cd139dc7SShuo Chen  }
30cd139dc7SShuo Chen
31cd139dc7SShuo Chen  void memberFunc()
32cd139dc7SShuo Chen  {
33cd139dc7SShuo Chen    printf("tid=%d, Foo::x_=%f\n", muduo::CurrentThread::tid(), x_);
34cd139dc7SShuo Chen  }
35cd139dc7SShuo Chen
36cd139dc7SShuo Chen  void memberFunc2(const std::string& text)
37cd139dc7SShuo Chen  {
38cd139dc7SShuo Chen    printf("tid=%d, Foo::x_=%f, text=%s\n", muduo::CurrentThread::tid(), x_, text.c_str());
39cd139dc7SShuo Chen  }
40cd139dc7SShuo Chen
41cd139dc7SShuo Chen private:
42cd139dc7SShuo Chen  double x_;
43cd139dc7SShuo Chen};
44cd139dc7SShuo Chen
45cd139dc7SShuo Chenint main()
46cd139dc7SShuo Chen{
47cd139dc7SShuo Chen  printf("pid=%d, tid=%d\n", ::getpid(), muduo::CurrentThread::tid());
48cd139dc7SShuo Chen
49cd139dc7SShuo Chen  muduo::Thread t1(threadFunc);
50cd139dc7SShuo Chen  t1.start();
51cd139dc7SShuo Chen  t1.join();
52cd139dc7SShuo Chen
53cd139dc7SShuo Chen  muduo::Thread t2(boost::bind(threadFunc2, 42),
54cd139dc7SShuo Chen                   "thread for free function with argument");
55cd139dc7SShuo Chen  t2.start();
56cd139dc7SShuo Chen  t2.join();
57cd139dc7SShuo Chen
58cd139dc7SShuo Chen  Foo foo(87.53);
59cd139dc7SShuo Chen  muduo::Thread t3(boost::bind(&Foo::memberFunc, &foo),
60cd139dc7SShuo Chen                   "thread for member function without argument");
61cd139dc7SShuo Chen  t3.start();
62cd139dc7SShuo Chen  t3.join();
63cd139dc7SShuo Chen
64cd139dc7SShuo Chen  muduo::Thread t4(boost::bind(&Foo::memberFunc2, boost::ref(foo), std::string("Shuo Chen")));
65cd139dc7SShuo Chen  t4.start();
66cd139dc7SShuo Chen  t4.join();
67cd139dc7SShuo Chen
682b2bf878SShuo Chen  {
692b2bf878SShuo Chen    muduo::Thread t5(threadFunc3);
702b2bf878SShuo Chen    t5.start();
712b2bf878SShuo Chen  }
722b2bf878SShuo Chen  sleep(2);
73cd139dc7SShuo Chen  printf("number of created threads %d\n", muduo::Thread::numCreated());
74cd139dc7SShuo Chen}
75