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
原创粉丝点击