ZThread跨平臺(tái)線程庫
ZThread 是一個(gè) C++ 的跨平臺(tái)線程開發(fā)包。
zthread庫的用法和Java的多線程很相似,名字都差不多,比如Thread,Runnable,^_^
舉個(gè)例子入門一下吧
在zthread里有一個(gè)任務(wù)的概念,任務(wù)就是要做的一件事,任務(wù)是怎么定義呢?
兩件事要做:一、繼承Runnable這個(gè)抽象類。 二、實(shí)現(xiàn)run接口
Runnable在源代碼中的定義如下:
class Runnable{
public:
virtual void run() = 0;
virual ~Runnable(){}
}
我們現(xiàn)在定義一個(gè)任務(wù),這個(gè)任務(wù)用來數(shù)數(shù)吧
//File: Counter.cpp
#include <iostream>
#include <zthread/Runnable.h>
#include <zthread/Thread.h>
using namespace std;
using namespace ZThread; // Zthread所有的變量,類等都在這個(gè)名字空間內(nèi)
class Counter : public Runnable
{
private:
int _id; // 任務(wù)的ID號(hào)
int _num; // 當(dāng)前數(shù)到幾
public:
Counter(int id):_id(id){}
void run() // 實(shí)現(xiàn)run函數(shù)
{
_num = 1;
while(_num <=50 )
{
cout <<_id << " " << _num << endl;
_num++;
}
}
};
int main()
{
try
{
Thread t(new Counter());
}
catch(Synchronization_Exception& e)
{
cerr << e.what() <<endl;
}
}
// end of file
然后編譯它
g++ -o test Counter.cpp -lZThread
最后邊的一個(gè)選項(xiàng)是編譯時(shí)候動(dòng)態(tài)連接到libZThread庫
然后運(yùn)行吧
./test
如果報(bào)錯(cuò)的話,按下邊方式運(yùn)行
LD_LIBRARY_PATH=/usr/local/lib/
這就是基本線程運(yùn)行的例子了~~~
