红联Linux门户
Linux帮助

undefined reference to 'pthread_create'问题解决方法

发布时间:2016-01-11 11:14:45来源:linux网站作者:chenxun2009

在GUN/linux下我们使用 #include <pthread.h>时会出现下面的错误:

undefined reference to 'pthread_create'
undefined reference to 'pthread_join'


出现这中问题原因:
pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。


问题解决:
在编译中要加 -lpthread参数
g++ -o thread thread.cpp  -lpthread


附上自己的写的小demo:
#include <iostream> 
#include <stdio.h> 
#include <pthread.h>
using namespace std; 
void * child1(void *arg)

char ch = 0; 
while ('=' != (ch = getchar())) 



}
void *child2(void *arg) 

while (1) 

cout << "chenxun"; 
sleep(3); 
printf("thread 2 get running.\n"); 


int main() 

pthread_t tid1, tid2; 
pthread_create(&tid1, NULL, child1, NULL); 
pthread_create(&tid2, NULL, child2, NULL); 
pthread_join(tid1, NULL); 
pthread_cancel(tid2); 
return 0; 
}