读书人

ZThread库在Linux上安装

发布时间: 2012-11-01 11:11:31 作者: rapoo

ZThread库在Linux下安装

?17???????? }
?18???????? void run() {
?19???????????? try {
?20???????????????? while (_count--) {
?21???????????????????? cout << "Counter " << _id << ": " << _count << endl;
?22???????????????????? Thread::sleep(10);
?23???????????????? }
?24???????????????? cout << "Counter " << _id << ": end" << endl;
?25???????????? } catch (Interrupted_Exception& e) {
?26???????????????? cerr << e.what() << endl;
?27???????????? }
?28???????? }
?29 };
?30
?31 int main() {
?32???? const int n = 5;
?33???? try {
?34???????? for (int i = 0; i < n; i++) {
?35?????????? Thread t(new Counter(10, i));
?36???????? }
?37???? } catch (Synchronization_Exception& e) {
?38???????? cerr << e.what() << endl;
?39???? }
?40 }

=============================================================

编译应该没问题,运行的时候可能会有错误: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? cp 到/usr/lib目录应该就可以运行了。

运行结果如下:

=============================================================

Counter 0: 9
Counter 1: 9
Counter 2: 9
Counter 1: 8
Counter 0: 8
Counter 3: 9
Counter 4: 9
Counter 0: 7
Counter 2: 8
Counter 3: 8
Counter 1: 7
Counter 4: 8
Counter 2: 7
Counter 0: 6
Counter 3: 7
Counter 1: 6
Counter 4: 7
Counter 0: 5
Counter 2: 6
Counter 3: 6
Counter 1: 5
Counter 4: 6
Counter 2: 5
Counter 0: 4
Counter 3: 5
Counter 1: 4
Counter 4: 5
Counter 0: 3
Counter 2: 4
Counter 3: 4
Counter 1: 3
Counter 4: 4
Counter 2: 3
Counter 0: 2
Counter 1: 2
Counter 3: 3
Counter 4: 3
Counter 1: 1
Counter 3: 2
Counter 0: 1
Counter 2: 2
Counter 4: 2
Counter 0: 0
Counter 2: 1
Counter 3: 1
Counter 1: 0
Counter 4: 1
Counter 0: end
Counter 0 completed!
Counter 1: end
Counter 1 completed!
Counter 4: 0
Counter 2: 0
Counter 3: 0
Counter 2: end
Counter 2 completed!
Counter 3: end
Counter 3 completed!
Counter 4: end
Counter 4 completed!

=============================================================

运行的结果不一定跟上面的结果完全一致,这正是多线程程序的特点:)

对于ZThread库和多线程编程的入门级介绍,请参阅Thinking in C++第二卷,如果已经对此熟练掌握,可以看看Parallel and Distributed Programming Using C++,这本书不仅提供了一些优秀的多线程库的介绍,更重要的是一些多线程编程思想的介绍和理解,值得一读。

?

读书人网 >UNIXLINUX

热点推荐