為什麼要用JThread呢,往簡單的說,我們的程式經常要考慮多線程的問題,跨平台編譯的問題,奈何Win32和linux下的多線程寫法差別相當的大,我們只好使用相當醜陋的
#ifdef WIN32
#else
#endif
這樣的代碼如果只是幾句也無所謂,要是多了的話搞得我們自己都不知道最主要的意圖是什麼了,而我們選擇JThread的話,就不用被這個苦惱了
往小的方面想,很多開源項目也依賴於其他一些開源項目,比如,JRtp就依賴JThread;所以裝一下這個庫也挺有用的吧
好了,先下載源碼或者到這裡http://research.edm.uhasselt.be/~jori/page/index.php?n=CS.Jthread
解壓一下
tar -xvf jrtplib-3.7.1.tar.bz2
我一般喜歡選擇預設安裝,即把這些庫安裝到/usr/local裡面,所以
./configure
make
make install
完成後記得確認一下,是不是將這個庫放入
共用庫搜尋路徑
不然編譯完成後執行過程中你會收到這個錯誤
error while loading shared libraries: libjthread-1.2.1.so: cannot open shared object file: No such file or directory
共用庫的搜尋路徑
可以將so複製到/usr/lib或者將其所在目錄添加到/etc/ld.so.conf
然後
ldconfig -v
我使用的是後者
或者這樣執行你的程式:
LD_LIBRARY_PATH=/usr/local/lib ./run
好了,現在可以動手寫個關於JThread的HelloWorld了
myfunc.h
#ifndef _MYFUNC_H_
#define _MYFUNC_H_
#include <jthread.h>
int print_func();
class mythread:public JThread{
public:
void *Thread() ;
};
#endif
myfunc.cpp
#include <iostream>
#include <string>
#include "myfunc.h"
int print_func(){
sleep(1);
std::cout << "hello!" << std::endl;
return 0;
}
void *mythread::Thread(){
JThread::ThreadStarted();
print_func();
return 0;
}
只有幾行的main函數
main.cpp
#include <iostream>
#include "myfunc.h"
int main(){
sleep(1);
//先運行一下看一下
std::cout << "建立線程" << std::endl;
mythread arr_t[10];
for(int i=0;i<10;i++){
arr_t[i].Start();
}
std::cout << "OVER!" << std::endl;
sleep(1);
return 0;
}
然後就是 makefile
makefile
objects = myfunc.o main.o
CXXFLAGS = -I/usr/local/include/jthread -g
COMMLIB = -lstdc++ -L/usr/local/lib -ljthread -lpthread
run : $(objects)
g++ -o run $(objects) $(COMMLIB)
main.o:myfunc.h
myfunc.o:myfunc.cpp myfunc.h
gcc -c myfunc.cpp $(CXXFLAGS)
.PHONY : clean
clean:
rm run $(objects)
make一下
運行一下
./run
run result
建立線程
OVER!
hello!
hello!
hello!
hello!
hello!
hello!
hello!
hello!
hello!
hello!
linbc@cheng-ubuntu:~/workspace/example_jthread$