C++11 thread

/*
注意在 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值