pthread的使用
【摘要】
写一个test_pthread.c,练习pthread的用法
#include <pthread.h>#include <unistd.h>#include <stdio.h> void *thread(void *str){ int i; for (i = 0; i ...
写一个test_pthread.c,练习pthread的用法
-
-
#include <pthread.h>
-
#include <unistd.h>
-
#include <stdio.h>
-
-
void *thread(void *str)
-
{
-
int i;
-
for (i = 0; i < 10; ++i)
-
{
-
sleep(2);
-
printf( "This in the thread : %d\n" , i );
-
}
-
return NULL;
-
}
-
-
int main()
-
{
-
pthread_t pth;
-
int i;
-
int ret = pthread_create(&pth, NULL, thread, NULL);
-
-
pthread_join(pth, NULL);
-
for (i = 0; i < 10; ++i)
-
{
-
sleep(1);
-
printf( "This in the main : %d\n" , i );
-
}
-
return 0;
-
}
编译的时候发现,报错对‘pthread_create’未定义的引用,由于pthread库不是Linux系统默认的库,连接时需要使用库libpthread.a,所以在使用pthread_create创建线程时,在编译中要加-lpthread参数:然后重新编译
gcc -o pthread pthread_test.c -lpthread
运行
./pthread
运行结果
文章来源: xintiaobao.blog.csdn.net,作者:心跳包,版权归原作者所有,如需转载,请联系作者。
原文链接:xintiaobao.blog.csdn.net/article/details/89240982
【版权声明】本文为华为云社区用户转载文章,如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)