在linux下使用ZThread

Java 语言,把并发机制包含在核心语言中,因为Java语言具有平台无关性。而C没有并发机制,C++标准中也因此并没有纳入并发机制。我们在windows平台下开发c++,当使用并发机制时往往使用的SDK win32 api。在《c++编程思想》一书中,作者提供了一种开源的跨平台的高级面向对象的线性和sycnchronization 库 -- ZThread 。

ZThread库的主页:http://zthread.sourceforge.net

上面的网站打不开。可以用下面到地址来下载。

源码Zthread下载地址: http://prdownloads.sourceforge.net/zthread/ZThread-2.3.2.tar.gz


一、在linux 下编译

        1.下载保存 文件到 /usr/local/src

         2. 解压

             cd /usr/local/src

             tar -zxvf ZThread-2.3.2.tar.gz

        3.编译安装

             cd ZThread-2.3.2

             ./configure --prefix=/usr/local/ZThread

            如果在./configure时遇到错误:

            error: C++ compiler cannot create executables 

            yum install gcc-c++

          然后继续:

           make

            在make时遇到错误:

            ../include/zthread/Guard.h: In destructor 'ZThread::Guard<LockType, LockingPolicy>::~Guard()':

            ../include/zthread/Guard.h:494: error: there are no arguments to 'isDisabled' that depend on a template parameter, so a declaration of 'isDisabled' must be available

           只需 先export CXXFLAGS=-fpermissive,然后再执行

          ./configure --prefix=/usr/local/ZThread

          make

          make install

二、linux下使用

        1.写文件      zthread0.h    

#ifndef LIFT_OFF_H
#define LIFT_OFF_H
#include <iostream>
#include "zthread/Runnable.h"
using namespace std;

class LiftOff : public ZThread :: Runnable{
  int countdown;
  int id;
public:
      LiftOff(int count,int ident=0):countdown(count),id(ident){}
      ~LiftOff(){
         cout << id << "completed " << endl;
      }
      void run(){
         while(countdown--){
             cout << id << ":" << countdown << endl; 
         }
         cout << id << " lift off " << endl;
      }
};
#endif

BasicThreads.cpp

#include "zthread0.h"
#include "zthread/Thread.h"
using namespace std;
using namespace ZThread;

int main(){
 try{
    Thread t(new LiftOff(10),true);
    cout << "Waiting for LiftOff " << endl;
   }catch(Synchronization_Exception& e){
     cerr << e.what() << endl;
   }
} ///:~
      2.编译链接加入ZThread库

        

 gcc BasicThreads.cpp -L /usr/local/ZThread/lib -I /usr/local/ZThread/include  -lstdc++ -lZThread

       注意 -L 后面接ZThread的安装路径/lib

      要加入-lstdc++,否则会有如下错误:  

    (.text+0x3a29): undefined reference to `std::basic_ostream<char, std::char_traits<char>

       要加入-lZThread,相当于加入附加依赖项ZThread.lib,否则会有如下错误:

     (.text+0xd1):XX.cpp: undefined reference to `ZThread::Thread::Thread(ZThread::Task const&, bool)'

     3.运行

      ./a.out

      可能会有错误:error while loading shared libraries: libZThread-2.3.so.2: cannot open shared object file: No such file or directory

       libZThread-2.3.so.2拷贝到/usr/lib下

      如: cp /usr/local/ZThread/lib/libZThread-2.3.so.2 /usr/lib

      然后运行OK ,输出如下所示:

Waiting for LiftOff 0:9

0:8
0:7
0:6
0:5
0:4
0:3
0:2
0:1
0:0
0 lift off
0completed
    


       

你可能感兴趣的:(多线程,C++,并发,linux,zthread)