多线程相关

在c++中使用std::thread定义线程对象,一个对象对应一个线程,几个线程可以在多线程设备上同时运行,测试用例如下:

// thread example

#include       // std::cout

#include         // std::thread

void foo()

{

  // do stuff...

}

void bar(int x)

{

  // do stuff...

}

int main()

{

  std::thread first (foo);    // spawn new thread that calls foo()

  std::thread second (bar,0);  // spawn new thread that calls bar(0)

  std::cout << "main, foo and bar now execute concurrently...\n";

  // synchronize threads:

  first.join();                // pauses until first finishes

  second.join();              // pauses until second finishes

  std::cout << "foo and bar completed.\n";

  return 0;

}

output

main, foo and bar now execute concurrently...

foo and bar completed.

std::thread_local 变量

被thread_local修饰的变量存在于整个线程周期,在线程开始时被生成,在线程结束时被销毁

参考链接:https://www.cnblogs.com/pop-lar/p/5123014.html

std::mutex 互斥锁

用于保存某一线程中的重要区域(critical section),该区域内的代码必须在当前线程内连续执行,mutex会发出信号保证当前线程的该段代码能够独占资源,等运行完之后再解锁。

// mutex example

#include       // std::cout

#include         // std::thread

#include           // std::mutex

std::mutex mtx;          // mutex for critical section

void print_block (int n, char c) {

  // critical section (exclusive access to std::cout signaled by locking mtx):

  mtx.lock();

  for (int i=0; i

  std::cout << '\n';

  mtx.unlock();

}

int main ()

{

  std::thread th1 (print_block,50,'*');

  std::thread th2 (print_block,50,'$');

  th1.join();

  th2.join();

  return 0;

}


output:

**************************************************

$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$$

若去掉互斥锁,则运行结果为:

$$$$$$$$$$$$$$$$$*$$**$**$*$*$$**$*$$*$*$*$*$*$*$*$*$***$*$***$*$***$*$$$*$*$**$*$$$*$**

************

在这个程序中,加上互斥锁之后使得两个线程顺序执行。

你可能感兴趣的:(多线程相关)