免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1589 | 回复: 5
打印 上一主题 下一主题

有关linux下多线程程序 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2006-06-23 12:48 |只看该作者 |倒序浏览
关于linux下多线程编程,小弟遇到了点麻烦,请各位指导一下,谢谢.

这是编译时的错误信息:
[root@localhost thread]# g++ -o mutilthread main.cpp
main.cpp: In function `int main()':
main.cpp:14: error: invalid conversion from `void*' to `void*(*)(void*)'
main.cpp:14: error:   initializing argument 3 of `int pthread_create(pthread_t*, const pthread_attr_t*, void*(*)(void*), void*)'
main.cpp:17: error: `exit' undeclared (first use this function)
main.cpp:17: error: (Each undeclared identifier is reported only once for each function it appears in.)



这是源代码:main.cpp
#include <stdio.h>
#include <pthread.h>
void thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.\n");
}

int main(void)
{
pthread_t id;
int i,ret;
ret=pthread_create(&id,NULL,(void *) thread,NULL);
if(ret!=0){
printf ("Create pthread error!\n");
exit (1);
}
for(i=0;i<3;i++)
printf("This is the main process.\n");
pthread_join(id,NULL);
return (0);
}

论坛徽章:
0
2 [报告]
发表于 2006-06-23 13:05 |只看该作者
ret=pthread_create(&id,NULL,(void *) thread,NULL);
把里面那个 (void *)thread 的强制转换去掉。

论坛徽章:
0
3 [报告]
发表于 2006-06-23 13:24 |只看该作者
void 类型和void *不一致,可以:
void thread(void)   
改为:
void *thread(void)
另外:exit在stdlib.h中,

论坛徽章:
0
4 [报告]
发表于 2006-06-23 18:03 |只看该作者

两个问题

1。编码问题
void thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.\n");
}
改为
void* thread(void)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.\n");
return NULL;
}

ret=pthread_create(&id,NULL,(void *) thread,NULL);
改为ret=pthread_create(&id,NULL, thread,NULL);
2。编译问题
g++ -o mutilthread main.cpp
改为
g++ -o mutilthread main.cpp -lpthread

论坛徽章:
0
5 [报告]
发表于 2006-06-28 14:02 |只看该作者
改为
void* thread(void*)
{
int i;
for(i=0;i<3;i++)
printf("This is a pthread.\n");
return NULL;
}

论坛徽章:
0
6 [报告]
发表于 2006-06-28 16:30 |只看该作者
错了一个地方:pthread_create(&id,NULL,(void *) thread,NULL);
把,(void *) thread改成,(void *) &thread
一切ok
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP