• 《BOOST程序库完全开发指南》 第12章 并发编程


    先看下Linux 下的 pthread 多线程例子:

    #include <pthread.h>
    #include <stdio.h>
    #include <time.h>
    
    void sleep(int sec)
    {
        clock_t delay = sec * CLOCKS_PER_SEC;
        clock_t start = clock();
        while(clock() - start < delay);
    }
    void fun1(){
        while(1){
             printf( "fun1");
        }
    }
    
    void fun2(){
        while(1){
             printf("fun2");
        }
    }
    
    int main(){
        pthread_t t1;
        pthread_t t2;
        pthread_create(&t1,NULL,(void *)fun1,NULL);
        pthread_create(&t2,NULL,(void *)fun2,NULL);
        //pthread_join(t1,NULL);    //阻塞等待线程结束
        //pthread_join(t2,NULL);
        sleep(3);
        return 0;
    }

    再看下 boost 的 thread 库的写法:

    #include <iostream>
    #include <boost/thread.hpp>
    #include <boost/bind.hpp>
    
    using namespace std;
    
    void print1(string str)
    {
        while(1)
        {
            cout<<str<<endl;
        }
    }
    
    void print2(string str)
    {
        while(1)
        {
            cout<<str<<endl;
        }
    }
    
    int main()
    {
        //boost::thread t1(boost::bind(print1,"print1"));
        //boost::thread t2(boost::bind(print2,"print2"));
        //thread的构造函数有三种
        boost::thread t1(print1,"print1");
        boost::thread t2(print2,"print2");
        t1.join();
    }

    boost 加锁:

    #include <iostream>
    #include <string>
    #include <boost/thread.hpp>
    #include <boost/thread/mutex.hpp>
    
    using namespace std;
    
    boost::mutex mx;
    
    void print(int id)
    {
        for(int i=0;i<10;++i)
        {
            boost::mutex::scoped_lock lock(mx);
            //如果这里没有加锁,cout中 "id:",id,"   i= ",i  可能会断开
            cout<<"id:"<<id<<"   i = "<<i<<endl;
        }
    }
    
    int main()
    {
        boost::thread t1(print,3),t2(print,4);
        t1.join();
        t2.join();
    }
  • 相关阅读:
    点子
    evil idea
    ubuntu 10.04.3 modify source.list
    点子
    ubuntu常用软件安装
    架构技术介绍网站
    点子
    点子
    【转发】上海地区工作,全国找网络底层技术开发大牛,旅游方面的创业项目。
    文本相似度计算余弦定理和广义Jaccard系数
  • 原文地址:https://www.cnblogs.com/tianyajuanke/p/2852644.html
Copyright © 2020-2023  润新知