begincsdn .NET 趴趴窝
[天行健,君子以自强不息]
[天道酬勤思]
以下代码是可以正确执行的,但唯一不足的是,单线程和多线程的执行效率几乎相同。究竟是什么原因还没搞清楚。
 
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/thread.hpp>

#include <geos/geos.h>
#include <vector>
#include "macros.h"
#include "threads.h"

using namespace std;

#pragma comment(lib,LIB_XD("geos_3_35"))

typedef boost::thread THREAD;

typedef boost::mutex MUTEX;
typedef Coordinate PT;

typedef boost::thread * PTHREAD;

int MAX_COUNT = 2;
int currentIndex = 0;

MUTEX mm;

void Union()
{  
    GeometryFactory factory;
    CoordinateArraySequenceFactory csf;

    CoordinateSequence* cs1 = csf.create(5,2);
    cs1->setAt(PT(0,0,0),0);
    cs1->setAt(PT(1,0,0),1);
    cs1->setAt(PT(1,1,0),2);
    cs1->setAt(PT(0,1,0),3);
    cs1->setAt(PT(0,0,0),4);
    LinearRing* ring1 = factory.createLinearRing(cs1);
    Geometry* p1 = factory.createPolygon(ring1,NULL);

    CoordinateSequence* cs2 = csf.create(5,2);
    cs2->setAt(PT(4,4,0),0);
    cs2->setAt(PT(4,5,0),1);
    cs2->setAt(PT(5,5,0),2);
    cs2->setAt(PT(5,4,0),3);
    cs2->setAt(PT(4,4,0),4);

    LinearRing * ring2 = factory.createLinearRing(cs2);
    Geometry* p2 = (factory.createPolygon(ring2,NULL));
    
    int index = 0;
    while(index < MAX_COUNT)
    {
        {
            LOCK(mm);
            index = ++currentIndex;
        }
        if(index % 1000 == 0) cout << "count " << index << endl;
        Geometry* poly = p1->Union(p2);
        //int number = poly->getNumGeometries();
        delete poly;
    }

    delete ring1;
    delete ring2;
}

int main(int argc, char* argv[])
{
    PTHREAD threads[8];
    clock_t start, finish;  
    start = clock();  
    bool enabledThreadCount = 8;
    for(int i = 0; i < enabledThreadCount ; i ++)
    {
        boost::thread * t = new boost::thread(&Union);
        threads[i] = t;
    }

    for(int i =0; i < enabledThreadCount ; i++)
    {
        threads[i]->join();
        delete threads[i];
    }
    
    finish = clock();
    cout << "该程序运行时间为" << ((double)(finish - start)) / CLOCKS_PER_SEC << endl;
    int pause;
    cin >> pause;
    return 0;
}

 
posted on 2012-07-22 13:15  begincsdn  阅读(7016)  评论(2编辑  收藏  举报