C++11 thread
来源:互联网 发布:手机端怎么找淘宝客服 编辑:程序博客网 时间:2024/06/09 19:17
/*注意在 Linux GCC4.6 环境下,编译时需要加 -pthread*/
/*C++的线程库的实现和 “现代操作系统”P75 页中的线程库模型是一致的,如果能明白 书中 所说的内容,理解 C++的线程库模型会容易一点*/
/*首先要明白线程库是为了多线程计算准备的,多线程计算遇到的问题在这里也会遇到*/
/* * thread 有ID,有HANDLE,也有join, detach这样的线程控制函数 * 但是,没有 create destroy 这样的函数 * 我初步的认为,create destroy 是在thread 的对象的构造函数和析构函数中实现的 */#include <thread>#include <stdio.h>using namespace std;void Print(char *s) { puts(s);}int main() { puts("Threading test..."); thread p(Print, (char *)"Hello world"); p.join(); return 0;}
/* * mutex 是互斥量,可以实现互斥访问 * 提供了基本的 lock unlock 操作 * 也有 try_lock操作 * 这些操作是基本操作,目前已经足够我的使用 */#include <thread>#include <mutex>#include <stdio.h>using namespace std;void Print(int size, char ch) { static mutex mx; mx.lock(); for (int i=0; i<size; ++i) { putchar(ch); } putchar('\n'); mx.unlock();}int main() { puts("Threading test..."); thread star(Print, 50, '*'); thread don(Print, 50, '.'); star.join(); don.join(); return 0;}
下面的代码引用自:http://www.cplusplus.com/reference/condition_variable/condition_variable_any/wait/
/* * condition_variable 是条件变量,可以实现同步访问 * 条件变量 需要与 互斥量一起使用 * 提供了基本的 wait notify_one notify_all 操作 * * 这些操作是基本操作,目前已经足够我的使用 */#include <thread>#include <mutex>#include <condition_variable>#include <stdio.h>std::mutex mtx;std::condition_variable_any cv;int cargo = 0;bool shipment_available() {return cargo!=0;}void consume (int n) { for (int i=0; i<n; ++i) { mtx.lock(); cv.wait(mtx,shipment_available); // consume: printf("%d\n", cargo); cargo=0; mtx.unlock(); }}int main (){ std::thread consumer_thread (consume,10); // produce 10 items when needed: for (int i=0; i<10; ++i) { while (shipment_available()) std::this_thread::yield(); mtx.lock(); cargo = i+1; cv.notify_one(); mtx.unlock(); } consumer_thread.join(); return 0;}
0 0
- Thread(C#)
- c thread
- thread.c
- something about thread(c#)
- linux + thread + c (一)
- C#Thread的使用
- 【c++】线程thread类
- c++thread学习(1)
- C++/MFC-线程Thread
- C++:线程(std::thread)
- C#--理解Thread.Sleep函数
- C#--理解Thread.Sleep函数
- 4.多线程实例:thread.c
- 4.多线程实例:thread.c
- C#Thread类—多线程
- C 的 Thread Pool 筆記
- Linux线程的thread.c
- C#Thread的Join方法
- slf4j.logback和commons-loging
- C语言总结
- 织梦 CMS 几处突破点
- web.xml中listener作用及使用--实现记录网站的客户登录日志, 统计在线人数
- form内使用ajax异步请求错误
- C++11 thread
- unity 利用2d toolkit 实现按帧改变碰撞监测范围
- Android中全局变量被系统回收的问题
- Android触摸事件详解
- PAT1015
- 黑马程序员——————文件IO
- C语言指针类型
- Bat的pushd和popd
- Android学习笔记:利用Tablelayout和viewpager实现防qq底部栏切换