为什么要用JThread呢,往简单的说,我们的程序经常要考虑多线程的问题,跨平台编译的问题,奈何Win32和linux下的多线程写法差别相当的大,我们只好使用相当丑陋的

linux下JThread编译及其HelloWorld#ifdef WIN32
linux下JThread编译及其HelloWorld
#else
linux下JThread编译及其HelloWorld
#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了



#include <jthread.h>

int print_func();

class mythread:public JThread{
public:
    
void *Thread() ;
};

#endif



#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函数


#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

 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

 

创建线程
OVER!
hello
!
hello
!
hello
!
hello
!
hello
!
hello
!
hello
!
hello
!
hello
!
hello
!
linbc
@cheng-ubuntu:~/workspace/example_jthread$ 


 

 

相关文章: