在linux下使用ZThread
Java 語言,把并發機制包含在核心語言中,因為Java語言具有平臺無關性。而C沒有并發機制,C++標準中也因此并沒有納入并發機制。我們在windows平臺下開發c++,當使用并發機制時往往使用的SDK win32 api。在《c++編程思想》一書中,作者提供了一種開源的跨平臺的高級面向對象的線性和sycnchronization 庫 -- ZThread 。
ZThread庫的主頁:http://zthread.sourceforge.net
上面的網站打不開??梢杂孟旅娴降刂穪硐螺d。
源碼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下使用
#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
????
???????
總結
以上是生活随笔為你收集整理的在linux下使用ZThread的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C++类的前置声明
- 下一篇: Linux下pdf读取乱码