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(); }}
阅读全文
0 0
- 【C#】线程与线程
- C -线程
- c++/c实现线程池
- 【C/C++】什么是线程安全
- C#lock线程同步
- c下的线程
- ThreadPool 线程池[c#]
- c#线程与枚举
- ThreadPool 线程池[c#]
- c# 实现线程
- ThreadPool 线程池[c#]
- linux C 线程学习
- c实现线程池
- C#|线程初体会
- linux c 线程锁
- 线程安全C/C++
- Linux C 线程(一)
- pthread_create用法 c线程
- Netscaler 之Load Blancing
- [Mac OS/iOS]反汇编工具Hopper分析Crash Log
- PHP面向对象——继承(个人笔记)
- 微服务架构实践之邮件通知系统改造
- Dumpzilla工具第615行bug的解决办法
- C++ 线程
- 美团A轮 合并回文子串 【dp】
- ActiveMQ服务器之间传输对象,项目A发送对象到项目B接收发送对象《二》
- spring mvc 任务定时器 @Scheduled
- CentOS7.0安装配置Storm集群
- 透明度
- 设置UserAgent让电脑浏览器访问微信手机网站
- 程序猿们_一二三四线城市你更愿意选择去哪里工作?
- LeetCode 513. Find Bottom Left Tree Value (C++)