C++ 线程

来源:互联网 发布:win10风扇控制软件 编辑:程序博客网 时间:2024/06/11 03:49

C++ thread

在任何一个时间点上,线程是可结合的(joinable),或者是分离的(detached)。一个可结合的线程能够被其他线程收回其资源和杀死;在被其他线程回收之前,它的存储器资源(如栈)是不释放的。相反,一个分离的线程是不能被其他线程回收或杀死的,它的存储器资源在它终止时由系统自动释放。

线程的分离状态决定一个线程以什么样的方式来终止自己。在默认情况下线程是非分离状态的,这种情况下,原有的线程等待创建的线程结束。只有当thread.join()函数返回时,创建的线程才算终止,才能释放自己占用的系统资源。而分离线程不是这样子的,它没有被其他的线程所等待,自己运行结束了,线程也就终止了,马上释放系统资源。
如果线程处于joinable状态,则只能只能被创建他的线程等待终止

#include <thread>thread t1(task1);//create and startthread t2(task2);thread t3;t1.joinable();  // truet3.joinable();  // falset1.join();      //wait for thread end   阻塞等待线程终止 释放 t2.join();t1.joinable();  //falset3.joinable();  //falset1.detach();    //分离的线程,不受约束,后台运行,直至结束t2.detach();t1.get_id();    // get thread idt2.get_id();std::thread::id main_thread_id = std::this_thread::get_id();
//多线程创建#include <thread>  //std::thread, std::this_thread::sleep_for#include <chrono>  // std::chrono::secondsvoid pause_thread(int n) {  this_thread::sleep_for (std::chrono::seconds(n));  cout << "pause of " << n << " seconds ended\n";}thread threads[5];cout << "Spawning 5 threads...\n";for (int i=0; i<5; ++i)    threads[i] = std::thread(pause_thread,i+1);cout << "Done spawning threads. Now waiting for them to join:\n";for (int i=0; i<5; ++i)    threads[i].join();cout << "All threads joined!\n";

output:

Spawning 5 threads...Done spawning threads. Now waiting for them to join:pause of 1 seconds endedpause of 2 seconds endedpause of 3 seconds endedpause of 4 seconds endedpause of 5 seconds endedAll threads joined!

互斥量:

int a = 0;std::mutex mtx;void t_task1(){    cout << "task 1 ID: " << get_id() << endl;    for (int i = 1; i <= 20;i++)    {        lock_guard<mutex> guard(mtx);//自动释放        a++;        cout <<"task1:"<< a << endl;    }}void t_task2(){    cout << "task 2 ID: " << get_id() << endl;    for (int i = 1; i <= 20;i++)    {        mtx.lock();        a++;        cout <<"task1:"<< a << endl;        mtx.unlock();    }}
原创粉丝点击