《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();
}
原文地址:https://www.cnblogs.com/tianyajuanke/p/2852644.html