红联Linux门户
Linux帮助

总算实现了linux多线程的编译,多线程编译错误

发布时间:2008-04-15 11:27:21来源:红联作者:gongji110
我按照书上写了个thrdcreat.c源文件如下:
/*
* thrdcreat.c -- Illustrate creating a thread
*/

#include
#include
#include
#include

void task1(int *counter);
void task2(int *counter);
void cleanup(int counter1, int counter2);

int g1 = 0;
int g2 = 0;

int main(int argc, char *argv[])
{
pthread_t thrd1, thrd2;
int ret;

/* Create the first thread */
ret = pthread_create(&thrd1,NULL,(void*)task1, (void*)&g1);
if(ret)
{
perror("pthread_create:task1");
exit(EXIT_FAILURE);
}

/* Create the second thread */
ret = pthread_create(&thrd2, NULL, (void*)task2, (void*)&g2);
if(ret)
{
perror("pthread_create:task2");
exit(EXIT_FAILURE);
}

pthread_join(thrd2,NULL); //第一个线程执行后等待,并被刮起,知道第二个线程执行完毕后第一个线程再继续执行
pthread_join(thrd1,NULL);
cleanup(g1, g2);
exit(EXIT_SUCCESS);
}

void task1(int *counter)
{
while(*counter < 5)
{
printf("task1 count:%d\n",*counter);
(*counter)++;
sleep(1);
}
}

void task2(int *counter)
{
while(*counter < 5)
{
printf("task2 count:%d\n",*counter);
(*counter)++;
//sleep(1);
}
}

void cleanup(int counter1, int counter2)
{
printf("total iterations:%d\n",counter1 + counter2);
}

本以为大功告成了呢,可是在编译的时候总是出现:
[hyj@localhost cfile]$ gcc -o thrdcreat thrdcreat.c
/tmp/ccorDWTW.o: In function `main':
thrdcreat.c:(.text+0x31): undefined reference to `pthread_create'
thrdcreat.c:(.text+0x76): undefined reference to `pthread_create'
thrdcreat.c:(.text+0xaa): undefined reference to `pthread_join'
thrdcreat.c:(.text+0xbd): undefined reference to `pthread_join'
collect2: ld 返回 1
没有定义pthread_create和pthread_join?不可能阿,我有头文件#include 的啊。
后来查了很多资料才发现线程的库在编译时要指定,不然就会出现这类错误。
解决这个问题的方法很简单,就是在编译的时候在gcc后面加上-lpthread即可。
[hyj@localhost cfile]$ gcc -o thrdcreat thrdcreat.c -lpthread
[hyj@localhost cfile]$ ./thrdcreat
task1 count:0
task2 count:0
task2 count:1
task2 count:2
task2 count:3
task2 count:4
task1 count:1
task1 count:2
task1 count:3
task1 count:4
total iterations:10
:0wpoi2
大功告成。
文章评论

共有 2 条评论

  1. haimeishan 于 2013-12-21 10:18:28发表:

    非常好

  2. iopto 于 2008-04-15 12:41:30发表:

    不错,学习了