如果引用了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文件链接成可执行文件时候,加这个动态库。