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

#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

大功告成。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值