#include <pthread.h>
#include <stdio.h>
//#include <stdlib.h>
void * func_0()
{
printf("This is thread 1!\n");
}
void * func_1()
{
printf("This is thread 2!\n");
}
int ThreadProc()
{
pthread_t tTid[2];
int i=0;
if(pthread_create(&tTid[0], 0, (void *)func_0, NULL))
{
exit(1);
}
if(pthread_create(&tTid[1], 0, (void *)func_1, NULL))
{
exit(1);
}
//for(i = 0; i < 2; i++)
// pthread_join(tTid[i], 0);
return 0;
}
int main()
{
return ThreadProc()
执行上述程序,假设把这段程序保存为1.c,一般会碰到以下三种错误:
1.如果你用gcc 1.c -o 1 它会报这么一个错 undefined reference to 'pthread_create' 原因是:pthread 库不是 Linux 系统默认的库,连接时需要使用静态库 libpthread.a,所以在使用pthread_create()创建线程,以及调用 pthread_atfork()函数建立fork处理程序时,需要链接该库。 此时你用gcc 1.c -o 1 -lpthread 就不会报这样的错了。
2.隐式声明与内建函数 ‘exit’ 不兼容 解决方法有以下两种,一:注释exit函数,然后改用return语句,可以正常编译且执行。二:添加头文件,stdlib.h可以正常编译与执行。第一种我没试过,第二种可以解决,因为这个头文件中包含这个声明:extern void exit (int __status) __THROW __attribute__ ((__noreturn__));
3.在./1时你会发现无法在linux的显示框中看到你程序中所要打印出来的东西,此时加上for(i = 0; i < 2; i++)
pthread_join(tTid[i], 0);
就可以解决。