linux下多线程编程问题收集
2014-03-30 20:19
239 查看
如果引用了pthread.h头文件,则在链接程序的时候要加上-lpthread选项(g++ -o -lpthread),如:
//test.cpp
1 #include<iostream>
2
3 #include<pthread.h>
4 #include<unistd.h>
5
6 using namespace std;
7
8 int kk = 0;
9
10 void* fun(void *p)
11 {
12 cout<<"a new thread"<<endl;
13
14 int count = 100;
15 while(count > 0)
16 {
17 kk++;
18 cout<<"this is new thread and kk="<<kk<<endl;
19
20 usleep(1000);
21 --count;
22 }
23
24 return p;
25 }
26
27 int main()
28 {
29 pthread_t pt;
30
31 int ret = pthread_create(&pt,NULL,fun,NULL);
32
33 cout<<"ret = "<<ret<<endl;
34 if(ret != 0)
35 {
36 cout<<"create thread error"<<endl;
37 //exit(1);
38 return 1;
39 }
40
41
42 int count = 100;
43 while(count > 0)
44 {
45 kk += 2;
46 cout<<"this is main thread and kk="<<kk<<endl;
47 usleep(1000);
48 --count;
49 }
50
51
52 pthread_join(pt,NULL);
53
54 return 0;
55
56 }
则编译该文件的Makefile可以写成:
//makefile
1 test.exe:test.o
2 g++ -o test.exe -lpthread test.o
3
4 test.o:test.cpp
5 g++ -c test.cpp
注意其中的-lpthread不要漏了,否则会链接出错。
-lpthread编译(应该是链接吧?)选项的作用是链接多线程的库.
在程序中用到了pthread.h头文件中的函数时需要加这个选项.
-lpthread,不应该加在编译参数里面,而应该加在链接里面,把所有.o文件链接成可执行文件时候,加这个动态库。
//test.cpp
1 #include<iostream>
2
3 #include<pthread.h>
4 #include<unistd.h>
5
6 using namespace std;
7
8 int kk = 0;
9
10 void* fun(void *p)
11 {
12 cout<<"a new thread"<<endl;
13
14 int count = 100;
15 while(count > 0)
16 {
17 kk++;
18 cout<<"this is new thread and kk="<<kk<<endl;
19
20 usleep(1000);
21 --count;
22 }
23
24 return p;
25 }
26
27 int main()
28 {
29 pthread_t pt;
30
31 int ret = pthread_create(&pt,NULL,fun,NULL);
32
33 cout<<"ret = "<<ret<<endl;
34 if(ret != 0)
35 {
36 cout<<"create thread error"<<endl;
37 //exit(1);
38 return 1;
39 }
40
41
42 int count = 100;
43 while(count > 0)
44 {
45 kk += 2;
46 cout<<"this is main thread and kk="<<kk<<endl;
47 usleep(1000);
48 --count;
49 }
50
51
52 pthread_join(pt,NULL);
53
54 return 0;
55
56 }
则编译该文件的Makefile可以写成:
//makefile
1 test.exe:test.o
2 g++ -o test.exe -lpthread test.o
3
4 test.o:test.cpp
5 g++ -c test.cpp
注意其中的-lpthread不要漏了,否则会链接出错。
-lpthread编译(应该是链接吧?)选项的作用是链接多线程的库.
在程序中用到了pthread.h头文件中的函数时需要加这个选项.
-lpthread,不应该加在编译参数里面,而应该加在链接里面,把所有.o文件链接成可执行文件时候,加这个动态库。
相关文章推荐
- 关于linux中多线程编程的一些初级问题
- Linux 多线程编程问题
- linux 多线程编程的信号问题
- Linux 多线程编程的问题(转)
- Linux 多线程编程----线程见同步问题
- Linux 系统应用编程——多线程经典问题(生产者-消费者)
- linux 多线程编程-读写者问题
- linux多线程编程——读者优先、写者优先问题
- Linux 多线程编程的问题(转)
- linux下 多线程编程 哲学家就餐问题
- Linux 系统应用编程——多线程经典问题(生产者-消费者)
- linux 进程编程问题汇总(一)
- 多线程编程之—问题提出
- 《转》Linux下的多线程编程
- 多线程编程之一——问题提出
- linux socket编程client关闭时server崩溃问题
- Linux环境多线程编程基础设施
- 多线程编程之一问题提出(转)
- linux高效率编程:epoll和多线程
- 多线程编程之一——问题提出