【C++编程】 多线程创建

线程创建

1.1 通过普通函数创建线程

1. 示例

#include <iostream>
#include <thread> 
using namespace std;
 
void func(int a, double b) {
    cout << a << ' ' << b << endl;
}
 
void func2() {
  cout << "hello!\n";
}
 
int main() 
{
  thread t1(func, 1, 2); //提供参数
  thread t2(func2);

  t1.join();
  t2.join();

  return 0;
}

1.2 通过类或对象创建线程

1. 示例

#include <thread>
#include <iostream>

class Function {
public:
  void operator()() {
    std::cout << "子线程" << std::endl;
  }
};

int main()
{
  Function object;
  std::thread t1(object); //可调用对象即可
  t1.join();
  std::thread t2((Function()));
  t2.join();
  std::cout << "主线程" << std::endl;
  return 0;
}

1.3 通过lambda表达式创建线程

1. 示例

#include <thread>
#include <iostream>
int main()
{
    std::thread t1([] { std::cout << "子线程" << std::endl; });
    t1.join();
    std::cout << "主线程" << std::endl;
    return 0;
}

2. 示例

#include <iostream>
#include <thread> 
using namespace std;

int main() 
{
  thread t1([](int a, double b){cout << a << ' ' << b << endl;}, 3, 4);

  cout << t1.get_id()  << "****" << endl;  
  t1.join();

  return 0;
}

 

带智能指针参数创建方式

#include <thread> 
#include <iostream> 
#include <thread> 

void printInfo(std::unique_ptr<int> ptr) { 
    std::cout << "子线程:"<<ptr.get() << std::endl; 
} 

int main()  
{ 
     std::unique_ptr<int> ptr(new int(100)); 
     std::cout << "主线程:" << ptr.get() << std::endl;   
     std::thread t(printInfo, std::move(ptr));     
     t.join(); 
     std::cout << "主线程:"<<ptr.get() << std::endl;  //主线程:00000000 move掉了 
     return 0; 
}
#include <stdio.h>
#include <stdlib.h>
#include <chrono>
#include <iostream>
#include <thread>

void thread_task(int n)
{
  std::this_thread::sleep_for(std::chrono::seconds(n));
  std::cout << "hello thread "
            << std::this_thread::get_id()
            << " paused " << n << " seconds" << std::endl;
}

int main(int argc, const char *argv[])
{
  std::thread threads[5];
  std::cout << "Spawning 5 threads...\n";
  for (int i = 0; i < 5; i++)
    threads[i] = std::thread(thread_task, i + 1);

  std::cout << "Done spawning threads! Now wait for them to join\n";
  for (auto &t : threads)
    t.join();

  std::cout << "All threads joined.\n";

  return EXIT_SUCCESS;
}

编译:

g++  --std=c++11 thread.cpp -lpthread -o thread

输出:

Spawning 5 threads...
Done spawning threads! Now wait for them to join
hello thread 140083526539008 paused 1 seconds
hello thread 140083518146304 paused 2 seconds
hello thread 140083509753600 paused 3 seconds
hello thread 140083501360896 paused 4 seconds
hello thread 140083492968192 paused 5 seconds
All threads joined.

 

通过调用类的成员函数创建线程

1.实例

#include <thread>
#include <iostream>
#include <thread>
class MM {
public:
    void print(int &num) {
    num = 1001;
    std::cout << "子线程:" << num << std::endl;
  }
};

int main()
{
  MM mm;
  int num = 10;
  std::thread t(&MM::print, mm, std::ref(num));
  t.join();
  return 0;
}

 

posted @ 2019-03-27 15:00  苏格拉底的落泪  阅读(115)  评论(0编辑  收藏  举报