1 下載 ZThread 2.3.2 zthread.sourceforge.net/download.html
2 解壓以後進行安裝
1)./configureCXXFLAGS=-fpermissive //千萬不要少了CXXFLAGS=-fpermissive,否則在make的時候會報錯。
2)sudo make
3)sudo make install
thread庫的用法和Java的多線程很相似,名字都差不多,比如Thread,Runnable,^_^
舉個例子入門一下吧
在zthread裏有一個任務的概念,任務就是要做的一件事,任務是怎麼定義呢?
兩件事要做:
一、繼承Runnable這個抽象類。
二、實現run接口
Runnable在源代碼中的定義如下:
classRunnable{
public:
virtual void run() = 0;
virual ~Runnable(){}
}
我們現在定義一個任務,這個任務用來數數吧
//File:Counter.cpp
#include<iostream>
#include<zthread/Runnable.h>
#include<zthread/Thread.h>
usingnamespace std;
using namespace ZThread; // Zthread所有的變量,類等都在這個名字空間內
classCounter : public Runnable
{
private:
int_id; // 任務的ID號
int_num; // 當前數到幾
public:
Counter(int id):_id(id){}
voidrun() // 實現run函數
{
_num = 1;
while(_num <=50 )
{
cout <<_id << " " << _num <<endl;
_num++;
}
}
};
intmain()
{
try
{
in id = 1;
Thread t(new Counter(id));
}
catch(Synchronization_Exception& e)
{
cerr << e.what() <<endl;
}
}
// end offile
然後編譯它
g++ -otest Counter.cpp -lZThread
最後邊的一個選項是編譯時候動態連接到libZThread庫
然後運行吧
./test
如果報錯的話,按下邊方式運行
LD_LIBRARY_PATH=/usr/local/lib/
這就是基本線程運行的例子了.